简体   繁体   English

jQuery 追加元素后立即为 div 元素返回高度 0

[英]jQuery returns height of 0 for div element immediately after appending element

I have a floating div that initially has no content.我有一个最初没有内容的浮动 div。 I use jQuery to append a set of elements to the div, and then immediately call the height method of the original div.我用jQuery到append一组元素到div中,然后马上调用原div的height方法。 The elements I am adding have a defined min-height in the stylesheet, while the floating div does not.我添加的元素在样式表中定义了最小高度,而浮动 div 则没有。 The problem is that when I call height on the original div, I get 0.问题是当我调用原始 div 的高度时,我得到 0。

If I use setTimeout to delay the call for even 1 millisecond, I get the proper height.如果我使用 setTimeout 将调用延迟 1 毫秒,我就会得到正确的高度。 My theory is that when I call the height method, the browser has not yet finished rendering the change to the DOM, so it hasn't yet set the hei?ht of the top level element.我的理论是,当我调用 height 方法时,浏览器还没有完成对 DOM 的渲染,所以它还没有设置顶级元素的高度。 This height will vary, so using a fixed height is out.这个高度会有所不同,所以使用固定高度是不可能的。 Does anyone know what might be causing this problem?有谁知道可能导致此问题的原因是什么?

This should depend on the size of dom.这应该取决于dom的大小。 If its large there will be slight delays.如果它很大,会有轻微的延迟。

If nothing works out then you may temporarily want to consider the deferred.then() function. Here s an example using jsFiddle: http://jsfiddle.net/yTTRq/如果没有任何效果,那么您可能暂时需要考虑 deferred.then() function。这是一个使用 jsFiddle 的示例: http://jsfiddle.net/yTTRq/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM