用jquery获取固定div的位置 [英] Get the position of a fixed div with jquery

查看:120
本文介绍了用jquery获取固定div的位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个位置固定的div,我希望在用户向下滚动页面时获取其位置相对于整个文档的位置值。



因此,假设我将div放在(x = 0,y = 0)上,然后用户向下滚动一下,现在,相对于文档,div打开(X = 0, Y = 300)。我希望得到这些信息,我想知道每个时刻该div的确切位置,而不是相对于整个文档,而不是窗口或浏览器。



<我已经尝试了很多东西,但似乎没有得到我想要的东西。



其中一个代码是,它不起作用固定div的情况



  var position = $(#fixed)。offset(); / *它获得相对于文档* / 
$(#fixed)。html(position.top)的div
固定的位置; / *它将获得的
值打印在divfixed* /

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



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






已解决:



该问题已由 codef0rmer 解决。 我错过了跟踪滚动以刷新固定div位置的值。我是个白痴。因此,最终代码可以很好地工作:

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

$(window)。 scroll(function(){
var position = $(#fixed)。offset();
$(#fixed)。html(position.top);
}) ;
})



谢谢大家,特别感谢codef0rmer。

您可以使用 .offset()来获取元素的当前坐标相对于文档,而 .position()来获取元素相对于其父抵消的当前坐标。


I have a div with position "fixed" and I want to get the value of its position relative to the whole document while the user scrolls down the page.

So, lets say I place the div on (x=0,y=0) and then the user scrolls down a bit and now, relative to the document, the div is on (X=0,y=300). I want to get that information, I want to know the exact position of that div in every moment, again, relative to the whole document, not to the window or the browser.

I've tried many things but nothing seems to get what I'm trying to.

One of them is this code, which does not work in the case of a fixed 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, and you can see that, when you scroll down, the value of the position of the div does not change.

If I am not wrong, the code should print a new value on the div everytime it changes its vertical position relative to the document. But it turns out that it does not happen.


SOLVED:

The question was solved by codef0rmer. I was missing to track the scrolling to refresh the value of the position of the fixed div. I was an idiot. So the final code works fine the way he wrote it:

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

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

And here you can see the running code.

Thank you everyone and specially to codef0rmer.

解决方案

you can use .offset() to get the current coordinates of the element relative to the document whereas .position() to get the current coordinates of an element relative to its offset parent.

这篇关于用jquery获取固定div的位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆