jquery追加元素位置始终为0 [英] jquery append element position always 0

查看:28
本文介绍了jquery追加元素位置始终为0的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm using jquery's append() method, to add elements (div) to parent element (div as well).

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

When calling the offset function of the parent div, i'm getting it's relative position just fine. When i'm calling the child element, i'm getting 0 as its relative position (top and left)

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

Anyone have any idea how to solve this problem? How can I get the position of dynamically added div?

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

输出:上:0 左:0

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

(it shows me the current scroll bar offset from the top)

推荐答案

返回值正确.来自 .position() 的 jquery 文档:

The returned value is correct. From the 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.

Unless it has styles, it's always going to be at 0,0.

您可能希望改用 .offset().

You might want to use .offset() instead.

这篇关于jquery追加元素位置始终为0的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆