jQuery在追加元素后立即为div元素返回0的高度 [英] jQuery returns height of 0 for div element immediately after appending element

查看:105
本文介绍了jQuery在追加元素后立即为div元素返回0的高度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个浮动的div,最初没有内容。我使用jQuery将一组元素附加到div,然后立即调用原始div的height方法。我添加的元素在样式表中具有定义的最小高度,而浮动div不包含。问题是当我调用原始div的高度时,我得到0.



如果我使用setTimeout来延迟甚至1毫秒的调用,我得到了正确的高度。我的理论是,当我调用height方法时,浏览器还没有完成渲染到DOM的变化,所以还没有设置顶级元素的hei?这个高度会有所不同,所以使用一个固定的高度。有没有人知道可能导致这个问题?

解决方案

如果没有什么可以,那么你可能暂时想考虑延期。 ()函数。以下是使用jsFiddle的示例:
http://jsfiddle.net/yTTRq/


I have a floating div that initially has no content. I use jQuery to append a set of elements to the div, and then immediately call the height method of the original div. The elements I am adding have a defined min-height in the stylesheet, while the floating div does not. The problem is that when I call height on the original div, I get 0.

If I use setTimeout to delay the call for even 1 millisecond, I get the proper height. 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. This height will vary, so using a fixed height is out. Does anyone know what might be causing this problem?

解决方案

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/

这篇关于jQuery在追加元素后立即为div元素返回0的高度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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