js中巧用cssText属性批量操作样式(转)

给一个HTML元素设置css属性,如

1
2
3
4
var  head= document.getElementById( "head" );
head.style.width =  "200px" ;
head.style.height =  "70px" ;
head.style.display =  "block" ;

这样写太罗嗦了,为了简单些写个工具函数,如

1
2
3
4
5
6
7
function  setStyle(obj,css){
   for ( var  atr  in  css){
     obj.style[atr] = css[atr];
   }
}
var  head= document.getElementById( "head" );
setStyle(head,{width: "200px" ,height: "70px" ,display: "block" })

发现 Google API 中使用了cssText属性,后在各浏览器中测试都通过了。一行代码即可,实在很妙。如

1
2
var  head= document.getElementById( "head" );
head.style.cssText= "width:200px;height:70px;display:bolck" ;

和innerHTML一样,cssText很快捷且所有浏览器都支持。此外当批量操作样式时,cssText只需一次reflow,提高了页面渲染性能。

但cssText也有个缺点,会覆盖之前的样式。如

1
< div  style="color:red;">TEST</ div >

想给该div在添加个css属性width

1
div.style.cssText = "width:200px;";

这时虽然width应用上了,但之前的color被覆盖丢失了。因此使用cssText时应该采用叠加的方式以保留原有的样式。

1
2
3
4
function  setStyle(el, strCss){
     var  sty = el.style;
     sty.cssText = sty.cssText + strCss;
}

使用该方法在IE9/Firefox/Safari/Chrome/Opera中没什么问题,但由于 IE6/7/8中cssText返回值少了分号 会让你失望。

因此对IE6/7/8还需单独处理下,如果cssText返回值没";"则补上

1
2
3
4
5
6
7
8
9
10
11
12
function  setStyle(el, strCss){
     function  endsWith(str, suffix) {
         var  l = str.length - suffix.length;
         return  l >= 0 && str.indexOf(suffix, l) == l;
     }
     var  sty = el.style,
         cssText = sty.cssText;
     if (!endsWith(cssText,  ';' )){
         cssText +=  ';' ;
     }
     sty.cssText = cssText + strCss;
}


function setStyle(el, strCss){

function endsWith(str, suffix) {
var rgx=new RegExp(suffix+"$",'g');
if(rgx.test(str)){
return true;
}
return false;
}
var sty = el.style,
cssText = sty.cssText;
if(!endsWith(cssText, ';')){
cssText += ';';
}
sty.cssText = cssText + strCss;

}

可以用正则去判断末尾分号,indexOf性能太低

function setStyle(el, strCss){
function endsWith(str, suffix) {
var rgx=new RegExp(suffix+"$",'g');
if(rgx.test(str)){
return true;
}
return false;
}
var sty = el.style,
cssText = sty.cssText;
if(!endsWith(cssText, ';')){
cssText += ';';
}
sty.cssText = cssText + strCss;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值