Set css attributes for an HTML element, as shown in figure
Copy codeThe Code is as follows:
Var head = document. getElementById ("head ");
Head. style. width = "200px ";
Head. style. height = "70px ";
Head. style. display = "block ";
This is too cool to write. In order to be simple, write a tool function, such
Copy codeThe Code is as follows:
Function setStyle (obj, css ){
For (var xcode in css ){
Obj. style [recognition] = css [recognition];
}
}
Var head = document. getElementById ("head ");
SetStyle (head, {width: "200px", height: "70px", display: "block "})
It is found that the cssText attribute is used in Google APIs, and all tests in various browsers are passed. Just a line of code. For example
Copy codeThe Code is as follows:
Var head = document. getElementById ("head ");
Head.style.css Text = "width: 200px; height: 70px; display: bolck ";
Like innerHTML, cssText is fast and supported by all browsers. In addition, cssText only needs one reflow operation to improve the page rendering performance.
However, cssText also has a disadvantage that it will overwrite the previous style. For example
Copy codeThe Code is as follows:
<Div style = "color: red;"> TEST </div>
You want to add the css attribute width to the div.
Copy codeThe Code is as follows:
Div.style.css Text = "width: 200px ;";
At this time, although the width is applied, the previous color is overwritten and lost. Therefore, when cssText is used, the overlay method should be used to retain the original style.
Copy codeThe Code is as follows:
Function setStyle (el, strCss ){
Var sty = el. style;
Sty.css Text = sty.css Text + strCss;
}
This method is no problem in IE9/Firefox/Safari/Chrome/Opera, but it will disappoint you if the returned value of cssText in IE6/7/8 is missing a semicolon.
Therefore, IE6/7/8 must be processed separately. If the return value of cssText is not ";", add
Copy codeThe Code is as follows:
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.css Text;
If (! EndsWith (cssText ,';')){
CssText + = ';';
}
Sty.css Text = cssText + strCss;
}
Related:
Http://www.w3.org/TR/DOM-Level-2-Style/css.html#CSS-CSSStyleDeclaration
Https://developer.mozilla.org/en/DOM/CSSStyleDeclaration