ryoakg
6/3/2016 - 2:08 PM

modify-style-by-js.html

<html>
  <head>
  </head>
  <body>
    <div id="box">
    </div>
    <script>
     var head = document.getElementsByTagName('head')[0];
     var box = document.getElementById('box');

     if (false){
       var style = box.style;
       style.width = '200px';
       style.height = '200px';
       style.backgroundColor = '#eed';
     }
     if (false){
       box.style.cssText = 'width:200px;height:200px;background-color:#eed';
     }
     if (true){
       var style = document.createElement('style');
       head.appendChild(style);
       var sheet = style.sheet;
       sheet.insertRule('#box{width:200px;height:200px;background-color:#eed}',
                        sheet.cssRules.length);
       console.log(sheet.cssRules.length);
     }
    </script>
  </body>
</html>