我正在尝试使用 jQuery
和 jQuery UI
拖动 <ul>
水平位于 <div>
内的元素.
我想获取位于 <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()
: Get the current coordinates of the first element in the set of matched elements, relative to the document.
position()
: Get the current coordinates of the first element in the set of matched elements, relative to the offset parent.
关于jQuery:元素偏移量()坐标相对于另一个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4270053/