小编m4r*_*4rk的帖子

用jquery获取固定div的位置

我有一个位置"固定"的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"*/
Run Code Online (Sandbox Code Playgroud)

在这里你可以找到正在运行的代码,你可以看到,当你向下滚动时,div的位置值不会改变.

如果我没有错,代码应该在每次更改相对于文档的垂直位置时在div上打印一个新值.但事实证明它并没有发生.


解决了:

这个问题是由codef0rmer解决的.我错过了跟踪滚动来刷新固定div的位置值.我是个白痴.所以最终代码的编写方式很好:

$(function () {
    var position = $("#fixed").offset();
    $("#fixed").html(position.top);

    $(window).scroll(function () {
       var position = $("#fixed").offset();
        $("#fixed").html(position.top);
    });
})
Run Code Online (Sandbox Code Playgroud)

在这里,你可以看到正在运行的代码.

谢谢大家,特别感谢codef0rmer.

html jquery position fixed

15
推荐指数
2
解决办法
3万
查看次数

标签 统计

fixed ×1

html ×1

jquery ×1

position ×1