get new x/y positions of element after scroll using jQuery

回眸只為那壹抹淺笑 提交于 2019-12-03 12:00:38

问题


Lets say I have an <a> tag as follows:

<body>
    <div class="wrapper">
        <a href="#" class="a1">Click Me</a>
    </div>
</body>

and my CSS are:

body{ padding:10px;}
.wrapper { height:1000px; width:500px;}

Currently I am using .offset() of Jquery to get the X/Y positions of <a> tag.

var offset = $(".a1").offset();
var top = offset.top;
var left = offset.left;

Now when I scroll the page and check of <a> tag's x,y co-ordinates, they remain the same, i.e. ineffective of page scrolling.
I want to get the new X,Y positions of <a> tag after scrolling the page related to the screen.
If this <a> tag gets hidden after scrolling down, I want its position in negative values.

Check this fiddle: http://jsfiddle.net/xQh5J/9/

Please help.


回答1:


The link element's position w.r.t. the document does not change when you scroll. To get the position of the element w.r.t. the window's top-left, you can take it's offset() and subtract the window's scrollTop form what you get:

var offset = $(".a1").offset();
var w = $(window);
alert("(x,y): ("+(offset.left-w.scrollLeft())+","+(offset.top-w.scrollTop())+")");

Demo: http://jsfiddle.net/xQh5J/10/



来源:https://stackoverflow.com/questions/16794700/get-new-x-y-positions-of-element-after-scroll-using-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!