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

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

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

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返回值少了分号会让你失望。

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

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

相关:

http://www.w3.org/tr/dom-level-2-style/css.html#css-cssstyledeclaration

https://developer.mozilla.org/en/dom/cssstyledeclaration

仅ie6/7/8下csstext返回值少了分号 

文章来自: