有一种方法可以批量应用多个CSS样式,以避免多次回流? [英] Is there a way to apply multiple CSS styles in a batch to avoid multiple reflows?

查看:134
本文介绍了有一种方法可以批量应用多个CSS样式,以避免多次回流?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道通过JavaScript直接改变元素的风格会导致回流。然而,我想知道是否可以在一个批次中改变多个样式值,只有一个回流?

解决方案

不是直接有一些关于最大限度地减少回流影响的好建议:



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



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


第二种方法是为元素定义一个新的
样式属性,
而不是将样式一分配给
一个。大多数情况下,这适合于
动态变化,如动画,
,其中新样式不能提前知道
。这可以使用
style
对象的cssText属性或使用setAttribute完成。
Internet Explorer不允许
第二个版本,需要第一个。
一些旧的浏览器,包括Opera
8,需要第二种方法,并且
不明白第一种。所以简单的
方法是检查第一个版本
是否受支持,然后使用它,然后将
返回到第二个(如果不是)。




  var posElem = document.getElementById('animation'); 
var newStyle ='background:'+ newBack +';'+
'color:'+ newColor +';'+
'border:'+ newBorder +';';
if(typeof(posElem.style.cssText)!='undefined'){
posElem.style.cssText = newStyle; //使用+ =保存现有样式
} else {
posElem.setAttribute('style',newStyle);
}


I know that altering element's style via JavaScript directly will cause a reflow. However, I was wondering if it is possible to alter multiple style values in a batch with only one reflow?

解决方案

Not directly but there are some good suggestions on minimising the impact of reflows here:

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

In short, try something like this:

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);
}

这篇关于有一种方法可以批量应用多个CSS样式,以避免多次回流?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆