从固定定位的浮动元素计算 "left" 和 "top" 值

Calculating "left" and "top" value from fixed positioned floating element

以下是我的代码:

HTML:

<div id="test">
This text is fixed in one spot
</div>

CSS:

#test{
    border:1px solid black;
    position: fixed;
    margin: 8px;
    right: 0px;
    bottom: 0px;
    height: 200px;
    width: 50%;
    z-Index: 4;
}

到目前为止,我可以在固定位置制作一个框并使其正确显示(高度为 200 像素,宽度为屏幕的 50%)。当屏幕宽度改变时宽度也会改变,但我遇到的问题是我想计算框的左上角像素位置,因为我不希望框的任何部分出现在任何 adsense 广告单元的顶部。我的广告单元位于屏幕左侧。

我在 javascript 中尝试通过获取框最左侧像素的值,如下所示:

<script>
alert(document.getElementById('test').left);
alert(document.getElementById('test').style.left);
</script>

而且我没有从任何一个消息框中收到号码。我得到的只是一片空白和 "undefined".

有没有一种方法可以计算框的左上角像素位置,而无需通过 javascript 计时器定期强制值?

不,我不想使用 Jquery。

我认为您正在寻找的是 offsetLeft and offsetTop 方法。

alert(document.getElementById('test').offsetLeft);
alert(document.getElementById('test').offsetTop);
#test{
    border:1px solid black;
    position: fixed;
    margin: 8px;
    right: 0px;
    bottom: 0px;
    height: 200px;
    width: 50%;
    z-Index: 4;
}
<div id="test">
This text is fixed in one spot
</div>