使用jQuery滚动后获取元素的新x/y位置 [英] get new x/y positions of element after scroll using jQuery

查看:272
本文介绍了使用jQuery滚动后获取元素的新x/y位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们说我有一个<a>标记,如下所示:

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

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

和我的CSS是:

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

目前,我正在使用Jquery的.offset()来获取<a>标签的X/Y位置.

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;

现在,当我滚动页面并检查<a>标签的x,y坐标时,它们保持不变,即页面滚动无效.
滚动与屏幕相关的页面后,我想获得<a>标记的新X,Y位置.
如果此<a>标记在向下滚动后被隐藏,我希望其位置为负值.

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.

检查此小提琴: http://jsfiddle.net/xQh5J/9/

请帮助.

推荐答案

链接元素的位置w.r.t.滚动时,文档不会更改.要获取元素的位置w.r.t. 窗口的左上角,您可以将其取为 offset()并减去窗口的scrollTop形式:

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())+")");

演示: http://jsfiddle.net/xQh5J/10/

这篇关于使用jQuery滚动后获取元素的新x/y位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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