简体   繁体   English

如何知道HTML元素何时准备就绪(呈现)?

[英]How to know when an Html Element is ready (rendered)?

I have some javascript that adds an element to the document. 我有一些JavaScript,可以向文档中添加元素。 Immediately after adding i am trying to obtain the element's clientWidth and clientHeight. 添加后,我立即尝试获取元素的clientWidth和clientHeight。 However I am seeing all properties related to size to be 0. But at a later point i notice that the size properties do get populated with actual size values (eventually). 但是,我看到与大小相关的所有属性均为0。但是稍后,我注意到大小属性的确填充了实际大小值(最终)。

How can I know when the size details are available for an added Html element? 我如何知道何时可以为添加的HTML元素使用尺寸详细信息? I have tried listening to various events, such as onload and onreadystatechange. 我试过听各种事件,例如onload和onreadystatechange。 However these events seem to only apply for the document itself, not for individual elements. 但是,这些事件似乎仅适用于文档本身,不适用于单个元素。

Thanks much. 非常感谢。

DOM changes are postponed until the javascript thread quits, therefore this doesn't work: DOM更改被推迟到javascript线程退出之前,因此不起作用:

someNode.addChild(someElem);
w = someElem.clientWidth // 0

You have to start a new thread in order to work with newly added element: 您必须启动一个新线程才能使用新添加的元素:

someNode.addChild(someElem);

setTimeout(function() {
     w = someElem.clientWidth // should work
}, 0)

Alternatively (and better), try listening to a DOM mutation event: 另外(更好),请尝试监听DOM突变事件:

document.body.addEventListener('DOMNodeInserted', function(e) {
    alert('div height=' + e.target.clientHeight)
})

d = document.createElement("div")
d.appendChild(document.createTextNode("hello"))
t = document.body.appendChild(d)

http://jsfiddle.net/rM5cJ/ http://jsfiddle.net/rM5cJ/

You could set an initial dictionary (object literal can be used)— where you set at the very first start of the document , and after each html being rendered you can do : 您可以设置一个初始词典(可以使用对象常量)—在文档的第一个开始处进行设置,并且在呈现每个html之后,您可以执行以下操作:

<div id='aaa'> </div>

<Script>myObject.Add('aaa',1,doSomethingLater) </script>

You can not use the onload event since it's relevant only for : img / body/iframes. 您不能使用onload事件,因为它仅与img / body / iframes有关。

The object can look like this : 该对象可以如下所示:

myObject =
{
 Add:function (a,b,cb){this[a]=b;cb(a,b)} 

}

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

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