我想向DOM添加元素,同时避免页面回流 我的问题:
var Span = document.createElement('span');
document.body.appendChild(Span);
// Span doesn't contain any child node
// and isn't setted or inherited any style
// so Span has width = height = 0
将DOM添加到DOM会导致页面回流吗?
// After adding Span to DOM,
// I need to add style and text to Span.
// In order to avoid page reflowing, I set style 'display:none' to Span.
Span.style.cssText = 'display:none;other:value';
Span.textContent = 'some text';
我可以使用style.cssText
属性来设置display:none
和其他css属性并避免页面回流吗?
或者我是否必须先设置style.display = none
以避免页面回流,然后再使用cssText
设置其他属性?
等待您的建议并感谢您的阅读!
答案 0 :(得分:1)
添加或更改DOM中的大多数内容都会导致重排。正如上面评论者所建议的那样,最好的方法是在DOM之外构建元素的子树,然后立即将它们全部附加:
var newDiv = document.createElement('div');
newDiv.style.someStyleProperty = 'someStyleValue'; // repeat as needed
newDiv.innerHTML = 'some tags and text';
document.body.appendChild(newDiv);
当您拨打appendChild
时,这将导致一次重绕。