jQuery:元素offset()相对于另一个元素的坐标

vit*_*tto 2 html css jquery jquery-ui

我正在尝试使用jQueryjQuery 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>
Run Code Online (Sandbox Code Playgroud)

cas*_*nca 7

看起来你想要position()而不是offset().来自jQuery文档:

offset():获取相对于文档的匹配元素集中第一个元素的当前坐标.

position():获取相对于偏移父元素的匹配元素集中第一个元素的当前坐标.