【问题标题】:Calculating "left" and "top" value from fixed positioned floating element从固定定位的浮动元素计算“左”和“上”值
【发布时间】:2016-05-16 23:40:22
【问题描述】:

以下是我的代码:

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>

我没有从任何一个消息框中得到一个号码。我得到的只是一个空白和“未定义”。

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

不,我不想使用 Jquery。

【问题讨论】:

  • 为什么不直接获取广告的高度以及低于该高度的框的位置?
  • 无论用户在页面下方有多远,我都希望该框保持在右下角。

标签: javascript html css position fixed


【解决方案1】:

我认为您正在寻找的是 offsetLeftoffsetTop 方法。

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>

【讨论】:

  • 似乎在这里工作。我希望它适用于所有浏览器。
猜你喜欢
  • 1970-01-01
  • 2013-11-30
  • 1970-01-01
  • 1970-01-01
  • 2011-06-12
  • 2012-04-14
  • 1970-01-01
  • 2011-12-05
  • 1970-01-01
相关资源
最近更新 更多