gpt4 book ai didi

javascript - jquery追加元素位置始终为0

转载 作者:行者123 更新时间:2023-12-03 10:51:34 24 4
gpt4 key购买 nike

我正在使用jquery的append()方法,将元素(div)添加到父元素(div)。

当调用父div的偏移函数时,我得到了它的相对位置。当我调用子元素时,我得到 0 作为其相对位置(顶部和左侧)

有人知道如何解决这个问题吗?如何获取动态添加的div的位置?

var $grid = $('#myDiv');
$grid.empty()
$grid.append("<div id="newDiv">...")
console.log($("#newDiv").position())

输出:顶部:0 左侧:0

(它显示当前滚动条距顶部的偏移量)

最佳答案

返回值正确。来自 jquery documentation for .position() :

Get the current coordinates of the first element in the set of matched elements, relative to the offset parent.

除非它有样式,否则它总是在 0,0。

您可能想使用.offset()相反。

关于javascript - jquery追加元素位置始终为0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28408021/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com