div相对于窗口的位置? [英] Position of a div relative to the window?

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

问题描述

试图找到div相对于窗口的位置.我有一个水平的div,我想获得相对于窗口的左值.因此,如果将第二个div滚动到窗口左侧,它将显示为"0".

Trying to find the position of a div, relative to the window. I've got a horizontal div and I want to get the left value relative to the window. So If I scroll the second div to the left of the window, it will read "0".

不确定没有父div的情况是否可行.这是我的小提琴: http://jsfiddle.net/FSrye/

Not sure if this is possible without a parent div. Here is my fiddle: http://jsfiddle.net/FSrye/

它应该在没有父div的情况下运行.

edit: it should function like this without a parent div.

http://jsfiddle.net/FSrye/1/

推荐答案

尝试根据元素相对于窗口滚动位置的位置来计算它:

Try calculating it as a function of the position of the element relative to the scroll position of the window: http://jsfiddle.net/va836/

 var position = $('selector').position().left - $(window).scrollLeft();

如果它不是顶级元素,您可能还必须考虑相对于其他元素的位置.

实际上,这甚至更容易-只需使用offset()并省略父母的计算即可.

Actually, it's even easier -- just use offset() and omit the calculation of the parents.

var position = $('selector').offset().left - $(window).scrollLeft();

这篇关于div相对于窗口的位置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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