gpt4 book ai didi

javascript - 有没有办法批量套用多个CSS样式,避免多次回流?

转载 作者:可可西里 更新时间:2023-11-01 01:40:26 26 4
gpt4 key购买 nike

我知道直接通过 JavaScript 更改元素的样式会导致重排。但是,我想知道是否可以通过一次回流批量更改多个样式值?

最佳答案

不是直接的,但是这里有一些关于最小化回流影响的好建议:

http://dev.opera.com/articles/view/efficient-javascript/?page=3

简而言之,尝试这样的事情:

The second approach is to define a new style attribute for the element, instead of assigning styles one by one. Most often this is suited to dynamic changes such as animations, where the new styles cannot be known in advance. This is done using either the cssText property of the style object, or by using setAttribute. Internet Explorer does not allow the second version, and needs the first. Some older browsers, including Opera 8, need the second approach, and do not understand the first. So the easy way is to check if the first version is supported and use that, then fall back to the second if not.

var posElem = document.getElementById('animation');
var newStyle = 'background: ' + newBack + ';' +
'color: ' + newColor + ';' +
'border: ' + newBorder + ';';
if( typeof( posElem.style.cssText ) != 'undefined' ) {
posElem.style.cssText = newStyle; // Use += to preserve existing styles
} else {
posElem.setAttribute('style',newStyle);
}

关于javascript - 有没有办法批量套用多个CSS样式,避免多次回流?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4207505/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com