jQuery:元素偏移量()坐标相对于另一个元素

标签 jquery html css 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>

最佳答案

看起来您需要 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/

相关文章:

javascript - 关于 Bootstrap 2 和 jQuery 1.7.2 的困惑

javascript - $(.class).empty 总是缺少一个元素

html - <thead> 和 <th> 与表格的宽度不匹配

jquery - 如何让我的网页以与在 Codepen 上相同的方式显示?

css - Font Awesome : Why isn't my arrow icon loading on an :after instance?

javascript - 什么是语义 Action ?

jquery - 使用 jquery 设置文本限制

jquery - 如何使用jquery迭代数组的数组

html - 单选按钮水平对齐

jquery - 定位父级 <html> 并设置 css