简体   繁体   English

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

[英]jQuery Get top offset relative to a specific div

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的偏移量和位置,但那些似乎没有得到我正在寻找的正确偏移量。

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> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM