給一個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回傳值少了分號
文章來自:https://www.cnblogs.com/snandy/archive/2011/03/12/1980444.html#undefined
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/65721.html
標籤:Html/Css
上一篇:何時使用 Em 與 Rem【轉】
