jQuery div 相对于窗口的位置?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5943796/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 20:04:29  来源:igfitidea点击:

Position of a div relative to the window?

jquerypositioning

提问by wesbos

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 相对于窗口的位置。我有一个水平 div,我想获得相对于窗口的左值。因此,如果我将第二个 div 滚动到窗口左侧,它将显示为“0”。

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

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

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

编辑:它应该像这样在没有父 div 的情况下运行。

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

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

回答by tvanfosson

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

尝试将其计算为元素相对于窗口滚动位置的位置的函数:http: //jsfiddle.net/va836/

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

You might also have to factor in the position relative to other elements if it's not a top level element.

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

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

实际上,它更容易——只需使用offset()并省略父母的计算。

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

回答by Paul Sham

I think you can use scrollLeft()on the window to get the horizontal scroll amount.

我认为您可以scrollLeft()在窗口上使用来获取水平滚动量。