javascript 如何获得相对于特定父级的偏移量?

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

How to get offset relative to a specific parent?

javascriptjquery

提问by Homam

I want to get the offset of an element relative to a specific parentnot the direct one and not the document.

我想获得一个元素相对于特定父元素的偏移量,而不是直接的,而不是文档。

I looked for that on the internet and found the offsetand positionJQuery methods. But seems they don't help me in my situation ( relative to a specific parent)

我在互联网上寻找它并找到了偏移量位置JQuery 方法。但似乎他们在我的情况下对我没有帮助(相对于特定的父母)

Any help!

任何帮助!

回答by Michael McTiernan

You can try this out:

你可以试试这个:

var offsetLeft = $('#myElement').position().left - $('#myElement').closest('#crazyAncestor').position().left;
var offsetTop = $('#myElement').position().top - $('#myElement').closest('#crazyAncestor').position().top;

回答by balexandre

you need to subtract as OffSet implies the navigator window

您需要减去,因为 OffSet 意味着导航器窗口

var offset = GetOffSet( $("#a"), $("#b") );

function GetOffSet( elem, elemParent ) {
    return elemParent.position().left - elem.parent().position().left;
}