[英]jQuery: Element offset() coordinates relative to another element
我正在嘗試使用jQuery
和jQuery UI
拖動水平位於<div>
內的<div>
<ul>
元素。
我想得到位於<li>
元素內部的按鈕的坐標,使它們在#the_parent
中心,但每次調整瀏覽器窗口時我得到的位置都會改變,我怎樣才能獲得相對於#the_parent
的位置?
<script type:"text/javascript">
$(document).ready (function () {
$(".button").click (function () {
var offset = $(this).offset();
alert (offset.left);
});
});
</script>
<style type="text/css">
#dragme li { float:left; list-style:none; }
#the_parent { width:100%; }
.spacer { width:100px; }
.button div { padding:5px; background-color:darkgrey; color:white; }
</style>
<!-- this is contained inside another div of width:600px and it's centered in the middle of the page -->
<div id="the_parent">
<ul id="dragme">
<li class="spacer"></li>
<li id="btn_01" class="button">
<div>click</div>
</li>
<li class="spacer"></li>
<li id="btn_02" class="button">
<div>click</div>
</li>
<li class="spacer"></li>
</ul>
</div>
看起來你想要position()
而不是offset()
。 來自jQuery文檔:
offset()
:獲取相對於文檔的匹配元素集中第一個元素的當前坐標。
position()
:獲取相對於偏移父元素的匹配元素集中第一個元素的當前坐標。
你想使用.position()而不是.offset() 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.