简体   繁体   English

按名称而不是索引获取 document.styleSheets?

[英]get document.styleSheets by name instead of index?

document.styleSheets is used with an index, document.styleSheets与索引一起使用,
but what If I want to use stylesheet.insertRule with a specific CSS file ?但是如果我想在一个特定的 CSS 文件中使用stylesheet.insertRule呢?

I know the file's name, which is injected to a page and at some point via JS.我知道文件的名称,它被注入到页面中,并在某个时候通过 JS 注入。

Use this, and keep in mind:使用它,并记住:

For security reasons, Opera and Mozilla will not allow you to access the cssRules collection of a stylesheet from another domain or protocol.出于安全原因,Opera 和 Mozilla 不允许您访问来自其他域或协议的样式表的 cssRules 集合。 Attempting to access it will throw a security violation error尝试访问它会引发安全违规错误

function setStyleRule (selector, rule, sheetName) {
    var sheets = document.styleSheets,
        stylesheet = sheets[(sheets.length - 1)];
    
    for( var i in document.styleSheets ){
        if( sheets[i].href && sheets[i].href.indexOf(sheetName + ".css") > -1 ) {
            stylesheet = sheets[i];
            break;
        }
    }
    
    if( stylesheet.addRule )
        stylesheet.addRule(selector, rule);

    else if( stylesheet.insertRule )
        stylesheet.insertRule(selector + ' { ' + rule + ' }', stylesheet.cssRules.length);
}

Update - shorter code:更新 - 更短的代码:

function getSetStyleRule(sheetName, selector, rule) {
    var stylesheet = document.querySelector('link[href*=' + sheetName + ']')

    if( stylesheet ){
        stylesheet = stylesheet.sheet
        stylesheet.insertRule(selector + '{ ' + rule + '}', stylesheet.cssRules.length)
    }

    return stylesheet
}

// Usage example
getSetStyleRule('main', 'body', 'background:red')

Why so complicated?为什么这么复杂? You can get a specific document stylesheet by ID or URL without looping through all the stylesheets in the document: var mysheet = $('link#id')[0].sheet;您可以通过 ID 或 URL 获取特定的文档样式表,而无需遍历文档中的所有样式表: var mysheet = $('link#id')[0].sheet; ... or ... var mysheet = $('link[href="/css/style.css"]')[0].sheet; ... 或 ... var mysheet = $('link[href="/css/style.css"]')[0].sheet;

Here is a minor adjustment to the answer by vsync.这是 vsync 对答案的小幅调整。

function addRule(stylesheetId, selector, rule) {
  var stylesheet = document.getElementById(stylesheetId);

  if (stylesheet) {
    stylesheet = stylesheet.sheet;

    if (stylesheet.addRule) {
      stylesheet.addRule(selector, rule);
    } else if (stylesheet.insertRule) {
      stylesheet.insertRule(selector + ' { ' + rule + ' }', stylesheet.cssRules.length);
    }
  }
}

Once you get the DOM object through document.getElementById you can use the 'sheet' property to access the actual styleSheet.通过 document.getElementById 获得 DOM 对象后,您可以使用“sheet”属性来访问实际的样式表。 So just make sure that you provide an ID for the styleSheet you want to change.因此,只需确保为要更改的样式表提供 ID。 Even if it is an external CSS file, just give it an ID.即使是外部CSS文件,也只要给它一个ID即可。

And here is my test code:这是我的测试代码:

 var index = 0; var items = [ { selector: "h1", rules: "color:#3333BB;font: bold 18px Tahoma;padding: 12px 0 0 0;" }, { selector: "p", rules: "padding:0;margin:0;background-color:#123456;color:#ABCDEF;"}, { selector: "b", rules: "font-weight:normal;"}, { selector: "i", rules: "color:#66FF66;" } ]; function addRule(stylesheetId, selector, rule) { var stylesheet = document.getElementById(stylesheetId); if (stylesheet) { stylesheet = stylesheet.sheet; if (stylesheet.addRule) { stylesheet.addRule(selector, rule); } else if (stylesheet.insertRule) { stylesheet.insertRule(selector + ' { ' + rule + ' }', stylesheet.cssRules.length); } } } $(document).ready(function () { $("button").click(function () { addRule("myStyles", items[index].selector, items[index].rules); index++; }); });
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script> <style id="myStyles"> div { border: solid 1px black; width: 300px; height: 300px; } </style> <button>Click Me 4 times slowly</button> <div> <h1>test</h1> <p>Paragraph One</p> <p>Paragraph with <b>bold</b> and <i>Italics</i></p> <p>Paragraph 3</p> </div>

Without jquery:没有jQuery:

 function addRule(stylename, selector, rule) { var stylesheet = document.querySelector(`link[href$="${stylename}.css"]`) if( stylesheet.addRule ) stylesheet.addRule(selector, rule); else if( stylesheet.insertRule ) stylesheet.insertRule(selector + ' { ' + rule + ' }', stylesheet.cssRules.length); } // example use addRule('styles.css', '.color', 'red')

This happened because of the address of CSS is different of the adress of the page.发生这种情况是因为 CSS 的地址与页面的地址不同。 To fix is just make the both have the some adress.修复只是让两者都有一些地址。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM