接受的答案来自 2014 年,现已过时。 setTimeout 可能有效,但不是最干净的,也不一定保证元素已添加到 DOM。
从 2018 年开始,您应该使用 MutationObserver 来检测元素何时被添加到 DOM。 现在所有现代浏览器(Chrome 26+、Firefox)都广泛支持 MutationObservers 14+、IE11、Edge、Opera 15+等)。
将元素添加到 DOM 后,您将能够检索其实际尺寸。
这是一个简单示例,说明如何使用 MutationObserver 来监听元素何时添加到 DOM。
为简洁起见,我使用 jQuery 语法来构建节点并将其插入到 DOM 中。
var myElement = $("<div>hello world</div>")[0];
var observer = new MutationObserver(function(mutations) {
if (document.contains(myElement)) {
console.log("It's in the DOM!");
observer.disconnect();
}
});
observer.observe(document, {attributes: false, childList: true, characterData: false, subtree:true});
$("body").append(myElement); // console.log: It's in the DOM!
observer 事件处理程序将在document 中添加或删除任何节点时触发。在处理程序内部,我们然后执行contains 检查以确定myElement 现在是否在document 中。
您不需要遍历存储在 mutations 中的每个 MutationRecord,因为您可以直接对 myElement 执行 document.contains 检查。
要提高性能,请将 document 替换为 DOM 中将包含 myElement 的特定元素。