javascript – 如何获取外部样式的cssText?

我已经尝试了几个小时来得到结果,但失败了,下面,我将发布我所做的所有,希望我能得到一些提示,BTW,谢谢.

从错误消息,是啊它的cssRules是null,肯定错误!

  <!DOCTYPE html>
  <html lang="en">
  <head>
  <meta charset="UTF-8">
  <link rel="stylesheet" href="index.css">
  <title>css style</title>
  <style type="text/css">
     #demo {
        font-size: 10px;    /*first css rule */ 
     }
     p {
        border: 1px solid green;  /*second one*/
     }
      </style>
    </head>
   <body>
   <div id="demo" style="color: red;">
   <p>how to access of document's css!</p>
  </div>
 </body>

外部css

    #demo {
         font-weight: 900;
      }
     p {
         padding: 20px;
    }

使用Javascript

   <script>
      /*1,to get the inline style, this maybe the most easy one*/
      var cssInline = document.getElementById('demo').style;
      var cssInText = cssInline.cssText, cssColor = cssInline.color;
      console.log(cssInText, cssColor);

      /*2.a to get the style in head*/
      var cssInHeada = document.getElementById('demo');
      // using the computed css of inline
      var cssHeadText = getComputedStyle(cssInHeada, null);
      console.log(cssHeadText);

      // 2.b to get the style directly
      var cssInHeadb = document.getElementsByTagName('style')[0];
      console.log(cssInHeadb.textContent);

     // 2.c or like this
     var cssInHeadc = document.styleSheets[1];
     console.log(cssInHeadc.cssRules[0].cssText); //per rule

     /*3, but I cant get the extenal style*/
     var cssExtenal = document.styleSheets[0];
     console.log(cssExtenal.cssRules[0].cssText);
     </script>

谢谢你们!

最佳答案 我怀疑在加载样式表之前你的JavaScript正在运行.试试这个:

document.addEventListener('DOMContentLoaded', function () {
  var cssExtenal = document.styleSheets[0];
  console.log(cssExtenal.cssRules[0].cssText);
}, false);

或者,如果您碰巧使用jQuery,这更通用:

$('document').ready(function(){
  var cssExtenal = document.styleSheets[0];
  console.log(cssExtenal.cssRules[0].cssText);
});

更新:另一种可能性是您使用Chrome并加载CSS跨域或使用file://协议. This appears to be a known issue and is not considered a bug.

点赞