jQuery jQuery获取相对于特定div的顶部偏移量

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

jQuery Get top offset relative to a specific div

javascriptjquerypositionoffset

提问by Zach Reed

With jQuery, how would you find the offset position relative to a specific container?

使用 jQuery,您将如何找到相对于特定容器的偏移位置?

For example, you have this:

例如,你有这个:

<body style="padding:20px"> 
<div id="top-container" style="margin-top:20px"> 
    <div id="one-level-container" style="margin-top:70px"> 
        <div id="two-level-container" style="margin-top:120px"> 
            <div id="ELEMENT" style="margin-top:10px"> 
            </div> 
        </div> 
    </div> 
</div>
</body>

(The padding and margin-top's are just there for examples.)

(填充和边距顶部仅用于示例。)

How would you check the position top of #ELEMENT to #top-container?

您将如何检查#ELEMENT 的顶部到#top-container 的位置?

I've tried using jQuery's offset and position, but those don't seem to get the correct offset that I'm looking for.

我试过使用 jQuery 的偏移量和位置,但那些似乎没有得到我正在寻找的正确偏移量。

回答by Steve Robbins

Use $.offset(), for example

使用$.offset(),例如

alert($("#ELEMENT").offset().top - $("#top-container").offset().top)
body {
    background: blue
}

div {
    padding: 20px
}

#top-container {
    background: green
}

#one-level-container {
    background: red
}

#two-level-container {
    background: black
}

#ELEMENT {
    background: orange
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<body style="padding:20px"> 
<div id="top-container" style="margin-top:20px"> 
    <div id="one-level-container" style="margin-top:70px"> 
        <div id="two-level-container" style="margin-top:120px"> 
            <div id="ELEMENT" style="margin-top:10px"> 
            </div> 
        </div> 
    </div> 
</div>
</body>