js中巧用cssText屬性批量操作樣式_javascript技巧
來源:懂視網
責編:小采
時間:2020-11-27 20:58:26
js中巧用cssText屬性批量操作樣式_javascript技巧
js中巧用cssText屬性批量操作樣式_javascript技巧:給一個HTML元素設置css屬性,如 代碼如下: var head= document.getElementById(head); head.style.width = 200px; head.style.height = 70px; head.style.display = block; 這樣寫太羅嗦了,為了簡單些寫個工
導讀js中巧用cssText屬性批量操作樣式_javascript技巧:給一個HTML元素設置css屬性,如 代碼如下: var head= document.getElementById(head); head.style.width = 200px; head.style.height = 70px; head.style.display = block; 這樣寫太羅嗦了,為了簡單些寫個工

給一個HTML元素設置css屬性,如
代碼如下:
var head= document.getElementById("head");
head.style.width = "200px";
head.style.height = "70px";
head.style.display = "block";
這樣寫太羅嗦了,為了簡單些寫個工具函數(shù),如
代碼如下:
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"})
發(fā)現(xiàn) Google API 中使用了cssText屬性,后在各瀏覽器中測試都通過了。一行代碼即可,實在很妙。如
代碼如下:
var head= document.getElementById("head");
head.style.cssText="width:200px;height:70px;display:bolck";
和innerHTML一樣,cssText很快捷且所有瀏覽器都支持。此外當批量操作樣式時,cssText只需一次reflow,提高了頁面渲染性能。
但cssText也有個缺點,會覆蓋之前的樣式。如
代碼如下:
TEST
想給該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
聲明:本網頁內容旨在傳播知識,若有侵權等問題請及時與本網聯(lián)系,我們將在第一時間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com
js中巧用cssText屬性批量操作樣式_javascript技巧
js中巧用cssText屬性批量操作樣式_javascript技巧:給一個HTML元素設置css屬性,如 代碼如下: var head= document.getElementById(head); head.style.width = 200px; head.style.height = 70px; head.style.display = block; 這樣寫太羅嗦了,為了簡單些寫個工