如何从用insertRule添加的样式中检索CSS文本?

时间:2019-05-15 11:29:55

标签: javascript css dom

我有一个标签,该标签的内容已通过insertRule函数动态添加。 我想检索相关样式的文本内容

我尝试过document.getElementById('style').innerHTMLdocument.getElementById('style').text,但它们返回空字符串

// Add style a tag to head
var style = document.createElement("style");
style.id = "style",
style.type = "text/css",
document.head.appendChild(style);
var sheet = style.sheet;
// Insert some stylesheet rules
sheet.insertRule("p {background-color: red}", sheet.length);
sheet.insertRule("p {color: white}", sheet.length);
// Try to retrieve the css text
document.getElementById('style').innerHTML; // returns ""
document.getElementById('style').text; // returns undefined 

我希望样式表中出现文本CSS。 例如,以上样式必须返回 p {background-color: red} p {color: white}

3 个答案:

答案 0 :(得分:1)

var style = document.createElement("style");
    style.id = "style",
    style.type = "text/css",
    document.head.appendChild(style);
    var sheet = style.sheet;
    // Insert some stylesheet rules
    sheet.insertRule("p {background-color: red}", sheet.length);
    sheet.insertRule("p {color: white}", sheet.length);
    sheet.insertRule("div {color: green}", sheet.length);

    function getRule(){
      var cssFullText = "";
      [...sheet.cssRules].forEach(({cssText})=> cssFullText += `${cssText} `);
      console.log(cssFullText)
    }
<p>Test line</p>
    <p>Test line</p>
    <button onClick="getRule()">Get css HTML</button>

答案 1 :(得分:0)

您快到了。样式表显然已成为document.styleSheets对象的一部分。

因此document.styleSheets[0].cssRules将返回附加到文档的styleSheets列表(数组)。

然后可以循环浏览每个样式表。

cssRules将为您提供样式表的cssRules数组。

同样,您可以遍历SecurityError: The operation is insecure.来访问在那里编写的规则。

注意:

如果您尝试访问cssRules,则Firefox会抛出import numpy as np import matplotlib.pyplot as plt import webview class Api: def plot(self,y): x=np.linspace(1,100,100) z=np.cos(x) plt.figure(1) plt.plot(x) plt.figure(2) plt.plot(x,z) plt.show() api = Api() webview.create_window('API example', width=1200, height=600, resizable=False, js_api=api,url="file:///C:/Users/aly_h/Downloads/FullWidthTabs/index.html")` 错误。

Read more about CSSStyleSheet interface.

答案 2 :(得分:0)

尝试这样。我添加了示例代码片段来获取所有样式标签。

function addStyle(styles) { 
              
  /* Create style document */ 
  var css = document.createElement('style'); 
  css.type = 'text/css'; 

  if (css.styleSheet)  
  css.styleSheet.cssText = styles; 
  else  
  css.appendChild(document.createTextNode(styles)); 

  /* Append style to the tag name */ 
  document.getElementsByTagName("head")[0].appendChild(css); 
  
  // Try to retrieve the css text
  var styleTag = document.getElementsByTagName('style');
  for(var i=0; i<styleTag.length;i++){
    console.log(styleTag[i].innerHTML); // returns
  }
} 

/* Set the style */ 
var styles = 'h1 { color: green }'; 
styles += ' body { text-align: center }'; 

/* Function call */ 
window.onload = function() { addStyle(styles) }; 

相关问题