【问题标题】:Create Styleshhet and insertRule/addRule创建 Styleshhet 和 insertRule/addRule
【发布时间】:2017-03-21 09:17:52
【问题描述】:

我试图用 JS 创建样式表并附加一些规则,但它不起作用。

if (style == null) {
  var style = document.createElement('style');
  style.setAttribute('type', 'text/css');
  style.setAttribute('data-style', 13);
  if (style.styleSheet) {
    style.styleSheet.cssText = '';
  } else {
    style.appendChild(document.createTextNode(''));
  }
  document.head.appendChild(style);

}
if (typeof style.insertRule === 'function') {
  style.insertRule("main > section[data-y='0']{top: 200px;}");
} else if (typeof style.addRule === 'function') {
  style.addRule("main > section[data-y='0']", "{top: 200px;}");
}

对不起,我是 Js 的新手。

谁能告诉我为什么这不起作用?

【问题讨论】:

    标签: javascript css grid styles stylesheet


    【解决方案1】:

    我有类似的任务,我的例子:

     $('head').append('<link rel="stylesheet" type="text/css" href="css/test.css">');
        var sheets = document.styleSheets;
        console.log(sheets) //need to know number of my file, in my case e.g. it was 2
        var sheet = document.styleSheets[2];
        //also you forgot add index in the end of next line
        sheet.insertRule("body { background-color: #000;  }", 1);
    

    这不是一个最好的例子,但它对我有用 我找到了关于这个任务的不错的文章 https://davidwalsh.name/add-rules-stylesheets

    【讨论】:

      【解决方案2】:

      知道了!

      addRule / insertRule 不是样式的函数!它是 style.sheet 的一个功能,我忘了设置索引,所以它应该是

      if (typeof style.sheet.insertRule === 'function') {
        style.sheet.insertRule("main > section[data-y='0']{top: 200px;}",0);
      } else if (typeof style.sheet.addRule === 'function') {
        style.sheet.addRule("main > section[data-y='0']", "{top: 200px;}",0);
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-12-07
        • 1970-01-01
        • 2012-02-15
        • 2013-11-29
        • 1970-01-01
        • 2019-08-24
        • 2018-07-23
        • 1970-01-01
        相关资源
        最近更新 更多