【发布时间】:2012-03-02 04:01:39
【问题描述】:
我有一个位置“固定”的 div,我想在用户向下滚动页面时获取其位置相对于整个文档的值。
所以,假设我将 div 放在 (x=0,y=0) 上,然后用户向下滚动一点,现在,相对于文档,div 位于 (X=0,y=300) .我想获取这些信息,我想知道该 div 在每一刻的确切位置,同样,相对于整个文档,而不是相对于窗口或浏览器。
我尝试了很多东西,但似乎没有得到我想要的东西。
其中一个是这段代码,在固定div的情况下不起作用:
var position = $("#fixed").offset(); /*it gets the position of the div
"fixed" relative to the document*/
$("#fixed").html(position.top); /*it prints the obtained
value on the div "fixed"*/
Here you can find the running code,你可以看到,当你向下滚动时,div的位置值没有改变。
如果我没记错的话,代码应该在每次更改其相对于文档的垂直位置时在 div 上打印一个新值。但事实证明它并没有发生。
已解决:
问题已由codef0rmer 解决。 我错过了跟踪滚动来刷新固定 div 位置的值。我是个白痴。所以最终的代码按照他写的方式运行良好:
$(function () {
var position = $("#fixed").offset();
$("#fixed").html(position.top);
$(window).scroll(function () {
var position = $("#fixed").offset();
$("#fixed").html(position.top);
});
})
还有here you can see the running code.
谢谢大家,特别感谢codef0rmer。
【问题讨论】:
标签: jquery html position fixed