使用 jQuery 滚动后获取元素的新 x/y 位置
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16794700/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
get new x/y positions of element after scroll using jQuery
提问by Prasad Jadhav
Lets say I have an <a>
tag as follows:
假设我有一个<a>
标签如下:
<body>
<div class="wrapper">
<a href="#" class="a1">Click Me</a>
</div>
</body>
and my CSS are:
我的 CSS 是:
body{ padding:10px;}
.wrapper { height:1000px; width:500px;}
Currently I am using .offset()
of Jquery to get the X/Y positions of <a>
tag.
目前我正在使用.offset()
Jquery 来获取<a>
标签的 X/Y 位置。
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.
现在,当我滚动页面并检查<a>
标签的 x,y 坐标时,它们保持不变,即页面滚动无效。
我想<a>
在滚动与屏幕相关的页面后获取标签的新 X、Y 位置。
如果<a>
向下滚动后此标签被隐藏,我希望它的位置为负值。
Check this fiddle: http://jsfiddle.net/xQh5J/9/
检查这个小提琴:http: //jsfiddle.net/xQh5J/9/
Please help.
请帮忙。
回答by techfoobar
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'stop-left, you can take it's offset()and subtract the window's scrollTop form what you get:
当您滚动时,链接元素在文档中的位置不会改变。要获取元素在窗口左上角的位置,您可以使用它的offset()并减去窗口的 scrollTop 形式:
var offset = $(".a1").offset();
var w = $(window);
alert("(x,y): ("+(offset.left-w.scrollLeft())+","+(offset.top-w.scrollTop())+")");