巧用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

相關文章
相關標籤/搜索