javascript - 如何计算 <li> 相对于其父容器的 offset()

标签 javascript jquery html css

我有一个 <li>它嵌套在包含 <ul> 的内部,我想要的是计算偏移量。但是有左上角的<ul>0, 0 .

所以我的 HTML 是:

<div style="margin: 0 auto; width: 760px; height: 760px; overflow: hidden;">
    <ul style="width: 2000px; height: 2000px; min-height: 2000px; position: relative;">
        <li style="position: relative; width: 40px; height: 40px;"></li>
    </ul>
</div>

我当前的 jQuery 是:

thePos = $('ul li').offset();
alert('X = '+thePos.left+', Y = 'thePos.top);

但是,这将返回不是 0, 0 的偏移量.我猜它是在计算相对于文档边缘而不是父容器的偏移量。

我该如何解决这个问题?

谢谢。

注意:position()也没有检索到正确的数字:(

最佳答案

尝试使用 position() 而不是 offset()

来自 jQuery 文档:

The .offset() method allows us to retrieve the current position of an element relative to the document. Contrast this with .position(), which retrieves the current position relative to the offset parent.

关于javascript - 如何计算 <li> 相对于其父容器的 offset(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3422580/

相关文章:

javascript - 有没有像 "correct"这样的东西用 React hooks 和 Typescript 定义状态?

javascript - 滚动以解决向上滚动的问题

javascript - 如何处理/跟踪文本框上的多个事件(由其他元素制作 onchange、onblur、onclick)

javascript - JQuery如何隐藏/显示具有唯一id的动态数量的div

JQuery增量搜索

javascript - HTML5 客户端数据加密 - 我有哪些选择?

html - 使用顶部的元素底部的粘性元素?

javascript - 将回车键聚焦到特定按钮

javascript - ImagesLoaded with Masonry, Object #<Object> 没有方法 'imagesLoaded'

jquery - 使用 jquery animate 方法在容器 div 周围移动框 div