<td>
background color.The first way you may come out with you mind, maybe is the CSSStyleDeclaration object. Simply using
element.style
. It is straightforward but difficult to manage.1 2 3 4 5 6 7 8 9 10 | //pure javascript var tds = document.getElementsByTagName( 'td' ); for ( var i = 0; i < tds.length; i++){ tds[i].style.backgroundColor = 'grey' ; } //jQuery shorthand $( 'td' ).each( function (i, el){ el.style.backgroundColor = 'grey' ; }); |
The second method is to play with the inline style attribute. Its very simlar with
element.style
except the style priority.1 2 3 4 5 6 7 8 | //pure javascript var tds = document.getElementsByTagName( 'td' ); for ( var i = 0; i < tds.length; i++){ tds[i].setAttribute( 'style' , 'background-color:grey' ); } //jQuery shorthand $( 'td' ).css( 'background-color' , 'grey' ); |
The third way I can think of is modifying the
className
. Actually it is quite hot, because it separate the JS ans CSS, it make the web site more manageable. And Object Oriented CSS is also rely on the className
. And its performance is good, for example we don't need to loop through all <td>
in our test case, we can directly add it to <table>
or <body>
.1 | .greyTD td{ background-color :grey } |
1 2 3 4 5 | //pure javascript document.body.className += ' greyTD' ; //jQuery shorthand $(document.body).addClass( 'greyTD' ); |
The final method I'd introduced is CSSStyleSheet, we dynamically create
<style>
and append it into the <head>
. It performance is as good as modify the className
, but it is more dynamic because no predefined CSS is needed. However, it is more difficult to manage and debug.1 2 3 4 5 6 7 8 9 10 11 12 13 | //pure javascript var style = document.createElement( 'style' ); style.type = 'text/css' ; document.getElementsByTagName( 'head' )[0].appendChild(style); var sheet = style.sheet ? style.sheet : style.styleSheet; var rules = sheet.cssRules ? sheet.cssRules : sheet.rules; var index = rules.length; if (sheet.insertRule){ // Standard browser sheet.insertRule( 'td{ background-color:grey }' , index); } else if (sheet.addRule){ // IE8 or below sheet.addRule( 'td' , 'background-color:grey' , index); } |
No comments:
Post a Comment