Javascript 如何在jQuery中获得相对于父级的偏移量()?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10954931/
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
How to get offset() relative to parent in jQuery?
提问by TK123
This gives me the position of some element from the left edge of the main window:
这给了我一些元素从主窗口左边缘的位置:
$('#bar').offset().left;
If that element is situated inside some other element and I wanted the position of #bar relative to #foo (it's parent), how can I get that?
如果该元素位于其他某个元素内,并且我想要 #bar 相对于 #foo(它的父元素)的位置,我怎样才能得到它?
<style>
#foo { width: 200px; margin: 0 auto; }
#foo #bar { width: 50px; margin: 0 auto; }
</style>
<div id="foo">
<span id="bar"></span>
</div>
I saw that there is a function called offsetParent()
but when console logged it doesn't seem like this function has any properties called left
or x
. So not sure if that can be used to get what I need.
我看到有一个函数被调用,offsetParent()
但是当控制台记录它时,这个函数似乎没有任何名为left
or 的属性x
。所以不确定是否可以用来获得我需要的东西。
So in my example above the offset should be something around 125px from the parent's edge rather than some thousands of pixels from the main windows edge.
因此,在我上面的示例中,偏移量应该是距父窗口边缘 125 像素左右,而不是距主窗口边缘的数千像素。
回答by Scorpion-Prince
Use the position() method.
使用 position() 方法。
$('#bar').position().left;
回答by Niet the Dark Absol
It's simple enough: get the offset of the element and substract the offset of its parent.
很简单:获取元素的偏移量并减去其父元素的偏移量。
var elem = $("#bar");
var offset = elem.offset().left - elem.parent().offset().left;
回答by Miguel
Position within a div relative to its parent:
在 div 中相对于其父级的位置:
In my case, when scroll changed the calculated offset also changed and it shouldn't so i ended up using pure javascript which is quicker anyway...
就我而言,当滚动更改时,计算出的偏移量也发生了变化,它不应该发生,所以我最终使用了速度更快的纯 javascript...
element.get(0).offsetTop
element.get(0).offsetTop
Other variation like Left is also possible element.get(0).offsetLeft
其他像 Left 这样的变体也是可能的element.get(0).offsetLeft
Conclusion
结论
element.offset().top or position() are not optimal for position relative cases.
element.offset().top 或 position() 对于位置相对情况不是最佳的。
回答by Max Snijders
offsetLeft = $('#bar').position().left;
offsetTop = $('#bar').position().top;