gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 21:35:56 26 4
gpt4 key购买 nike

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

例如,您有这个:

<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>

(内边距和顶部边距仅作为示例。)

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

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

最佳答案

例如使用$.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>

关于javascript - jQuery 获取相对于特定 div 的顶部偏移量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17218765/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com