如何获得外部风格的cssText?

时间:2016-01-19 14:43:35

标签: javascript css

我已经尝试了几个小时来获得结果,但是失败了,下面,我将发布我已经完成的所有内容,希望我能得到一些提示,顺便说一句,谢谢。

来自错误消息,是的它 cssRules 是空的,肯定是错误的!

  <!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>

谢谢你们!

1 个答案:

答案 0 :(得分:1)

我怀疑在加载样式表之前你的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.