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

标签 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>

谢谢你们!

最佳答案

我怀疑您的 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:// 协议(protocol)。 This appears to be a known issue and is not considered a bug.

关于javascript - 如何获取外部样式的cssText?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34879704/

相关文章:

javascript - 我怎样才能用javascript获取宽度的值

javascript - 停止将窗口大小调整到 768px 以下

javascript - Bootstrap 大下拉菜单不同宽度大小

html - CSS 过渡在 chrome 和 IE 中晃动

javascript - 添加更多内容时 Div 高度不会调整大小

css - 如何限制 body 高度到视口(viewport)

javascript - webpack 和 kafka-node 集成

javascript - 如何在不换行的情况下通过文本选择创建工具提示?

javascript - Angularjs: Controller 中的 $filter 返回的数据仍然与原始对象绑定(bind)

javascript - 使用 .offset() 相对于动态表格数据设置表格位置