get new x/y positions of element after scroll usin

2020-05-26 11:58发布

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条回答
Explosion°爆炸
2楼-- · 2020-05-26 12:36

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/

查看更多
登录 后发表回答