[英]Javascript: unable to get height of newly created element
After updating the DOM with a new element (ei body.append(html)), I cannot immediately get the height of the newly updated element (eg body.height()). 用新元素(ei body.append(html))更新DOM后,我无法立即获得新更新元素的高度(例如body.height())。 A partial fix is setting a time interval and getting the height at the end of time interval (setTimeout("alert(body.height)", 500)).
部分修复是设置时间间隔并在时间间隔结束时获得高度(setTimeout(“alert(body.height)”,500))。
Any better ideas? 有更好的想法吗? Like a callback after DOM completely updates?
就像DOM完全更新后的回调一样? Thanks.
谢谢。
Edit: This only happens when there is a lot going on in the background (ie when page first loads). 编辑:这只发生在后台有很多事情发生时(即首次加载页面时)。 It would seem like the page update is almost instantaneous if nothing else is being processed.
如果没有其他任何处理,似乎页面更新几乎是即时的。 What I need is a callback, or an indicator of when the DOM is reformed!
我需要的是一个回调,或DOM重组时的指示!
Edit: The problem is from the browser being 'distracted' by other processes, which makes the browser unable to update immediately after the append of the element. 编辑:问题来自浏览器被其他进程“分心”,这使得浏览器无法在元素追加后立即更新。 How do I fix this?
我该如何解决?
The timeout method works because the rendering engine is given a chance to display the new element there by giving it a change to render it and thus assigning it a height. 超时方法有效,因为渲染引擎有机会在那里显示新元素,给它一个更改来渲染它,从而为它赋予一个高度。
You can set the timeout to 0 and still have the same effect. 您可以将超时设置为0并仍然具有相同的效果。
With jQuery works fine for me. 使用jQuery对我来说很好 。
In the jsfiddle demo I put the next code: 在jsfiddle演示中我放了下一个代码:
$(function(){
var jTest = $('#test');
console.log('The height:',jTest.innerHeight(),jTest.height()); //Show me 'The height: 20 20'
jTest.append('<div><br/>How are you?</div>');
console.log('The height:',jTest.innerHeight(),jTest.height()); //Show me 'The height: 60 60'
});
Unless you mean javascript only solution or put a jsFiddle demo to show your error. 除非你的意思是javascript解决方案或放一个jsFiddle演示来显示你的错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.