Element.height()不正确,因为浏览器还没有完成渲染? [英] Element.height() incorrect because browser hasn't finished rendering it?

查看:159
本文介绍了Element.height()不正确,因为浏览器还没有完成渲染?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将div1附加到div2然后获取div2的height()。如果我在调用height()之前等待50ms,我会得到不同的高度。看起来我在浏览器完成渲染div1之前得到了高度。任何人都知道如何解决这个问题。我添加了很多元素,需要在每个元素之后检查高度,因此在每个元素之间有一个延迟似乎可以加起来相当延迟。

I am appending div1 into div2 and then getting the height() of div2. If I wait 50ms before calling height() I get a different height. It seems like I am getting the height before the browser finishes rendering div1. Anyone have an idea as to how I can fix this. I am adding quite a few elements and need to check the height after every one, so having a delay between each seems like it could add up to quite the delay.

$(div2).append(div1);
console.log(div2.height()) // 295

where as...

$(div2).append(div1);
window.setTimeout(function(){
    console.log(div2.height()) // 245
},50)


推荐答案

您可以请求强制布局的某些属性。例如,如果您请求以下任何属性:

There are certain properties you can request that will force a layout. For example, if you request any of these properties:


  • offsetTop

  • offsetLeft

  • offsetWidth

  • offsetHeight

  • scrollTop / Left / Width / Height

  • clientTop / left / Width / Height

  • offsetTop
  • offsetLeft
  • offsetWidth
  • offsetHeight
  • scrollTop/Left/Width/Height
  • clientTop/Left/Width/Height

浏览器将在返回值之前布置该元素。如果您的布局很复杂,则可能需要在多个对象上请求属性才能获得多个项目的正确布局。

the browser will layout that element before returning the value. If you have a complicated layout, you may need to request properties on more than one object to get proper layout of several items.

请参阅此答案这篇文章了解更多细节和概念的工作演示。

See this answer and this article for more details and working demos of the concept.

这篇关于Element.height()不正确,因为浏览器还没有完成渲染?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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