Javascript:无法获取新创建元素的高度
使用新元素(ei body.append(html))更新 DOM 后,我无法立即获取新更新元素的高度(例如 body.height())。部分修复是设置时间间隔并获取时间间隔结束时的高度 (setTimeout("alert(body.height)", 500))。
还有更好的想法吗?比如 DOM 完全更新后的回调?谢谢。
编辑: 仅当后台发生很多事情时(即页面首次加载时)才会发生这种情况。如果没有处理其他任何事情,页面更新似乎几乎是瞬时的。我需要的是回调,或者 DOM 何时被改革的指示器!
编辑: 问题在于浏览器被其他进程“分散注意力”,这使得浏览器无法在添加元素后立即更新。我该如何解决这个问题?
After updating the DOM with a new element (e.i. body.append(html)), I cannot immediately get the height of the newly updated element (e.g. 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)).
Any better ideas? Like a callback after DOM completely updates? Thanks.
Edit:
This only happens when there is a lot going on in the background (i.e. 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!
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
超时方法之所以有效,是因为渲染引擎有机会通过更改渲染元素并为其分配高度来显示新元素。
您可以将超时设置为0,仍然具有相同的效果。
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.
使用 jQuery 对我来说很好。
在 jsfiddle 演示中,我放置了下一个代码:
除非您指的是仅 javascript 解决方案或放置 jsFiddle 演示来显示您的错误。
With jQuery works fine for me.
In the jsfiddle demo I put the next code:
Unless you mean javascript only solution or put a jsFiddle demo to show your error.