巧用cssText属性批量操做样式【转】

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

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

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

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属性,后在各浏览器中测试都经过了。一行代码便可,实在很妙。如浏览器

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

和innerHTML同样,cssText很快捷且全部浏览器都支持。此外当批量操做样式时,cssText只需一次reflow,提升了页面渲染性能。函数

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

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

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

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

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

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

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

所以对IE6/7/8还需单独处理下,若是cssText返回值没";"则补上code

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

相关:htm

http://www.w3.org/TR/DOM-Level-2-Style/css.html#CSS-CSSStyleDeclaration

https://developer.mozilla.org/en/DOM/CSSStyleDeclaration

仅IE6/7/8下cssText返回值少了分号 

文章来自:https://www.cnblogs.com/snandy/archive/2011/03/12/1980444.html#undefined

相关文章
相关标签/搜索