div相对于窗口的位置? [英] Position of a div relative to the window?
问题描述
试图找到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.
推荐答案
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屋!