document.styleSheets与索引一起使用,
但是,如果我想对特定的CSS文件使用stylesheet.insertRule怎么办?

我知道文件名,该文件名注入(inject)到页面中,有时通过JS注入(inject)。

最佳答案

使用这个,并记住:

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);
}

更新-较短的代码:
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')

关于javascript - 通过名称而不是索引获取document.styleSheets?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/1679577/

10-11 22:12
查看更多