如何使用Javascript添加CSS规则(如强{颜色:红色})?


当前回答

这是Chris Herring的解决方案的一个稍微更新的版本,考虑到你也可以使用innerHTML,而不是创建一个新的文本节点:

function insertCss( code ) {
    var style = document.createElement('style');
    style.type = 'text/css';

    if (style.styleSheet) {
        // IE
        style.styleSheet.cssText = code;
    } else {
        // Other browsers
        style.innerHTML = code;
    }

    document.getElementsByTagName("head")[0].appendChild( style );
}

其他回答

另一种选择是使用JQuery存储元素的内联样式属性,然后附加到它,然后用新值更新元素的样式属性。如下:

function appendCSSToElement(element, CssProperties)
        {
            var existingCSS = $(element).attr("style");

             if(existingCSS == undefined) existingCSS = "";

            $.each(CssProperties, function(key,value)
            {
                existingCSS += " " + key + ": " + value + ";";
            });

            $(element).attr("style", existingCSS);

            return $(element);
        }

然后用新的CSS属性作为对象执行它。

appendCSSToElement("#ElementID", { "color": "white", "background-color": "green", "font-weight": "bold" });

这可能不是最有效的方法(我愿意接受关于如何改进这一点的建议。:)),但它绝对有效。

下面是我的通用函数,它参数化了CSS选择器和规则,如果你想添加到特定的表中,它还可以选择一个CSS文件名(区分大小写)(否则,如果你不提供CSS文件名,它将创建一个新的样式元素并将其附加到现有的头部)。它最多创建一个新的样式元素,并在以后的函数调用中重用它)。适用于FF, Chrome和IE9+(可能更早,未经测试)。

function addCssRules(selector, rules, /*Optional*/ sheetName) {
    // We want the last sheet so that rules are not overridden.
    var styleSheet = document.styleSheets[document.styleSheets.length - 1];
    if (sheetName) {
        for (var i in document.styleSheets) {
            if (document.styleSheets[i].href && document.styleSheets[i].href.indexOf(sheetName) > -1) {
                styleSheet = document.styleSheets[i];
                break;
            }
        }
    }
    if (typeof styleSheet === 'undefined' || styleSheet === null) {
        var styleElement = document.createElement("style");
        styleElement.type = "text/css";
        document.head.appendChild(styleElement);
        styleSheet = styleElement.sheet;
    }

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

这是Chris Herring的解决方案的一个稍微更新的版本,考虑到你也可以使用innerHTML,而不是创建一个新的文本节点:

function insertCss( code ) {
    var style = document.createElement('style');
    style.type = 'text/css';

    if (style.styleSheet) {
        // IE
        style.styleSheet.cssText = code;
    } else {
        // Other browsers
        style.innerHTML = code;
    }

    document.getElementsByTagName("head")[0].appendChild( style );
}

在现代浏览器中,您可以使用document。adoptedStyleSheets添加CSS。

const sheet = new CSSStyleSheet();
sheet.replace("strong { color: red; }");
document.adoptedStyleSheets = [...document.adoptedStyleSheets, sheet];

这种方法的一个优点是,您甚至不需要等待<head>元素可用,这可能是早期运行的浏览器扩展代码所关注的问题。

下面是一个示例模板来帮助您入门

不需要任何库,只使用javascript注入HTML和CSS。

这个函数是从上面的@Husky用户那里借来的

如果你想运行一个tampermonkey脚本,并想在网站上添加一个切换覆盖(例如,一个笔记应用程序),这很有用。

// INJECTING THE HTML document.querySelector('body').innerHTML += '<div id="injection">Hello World</div>'; // CSS INJECTION FUNCTION //https://stackoverflow.com/questions/707565/how-do-you-add-css-with-javascript function insertCss( code ) { var style = document.createElement('style'); style.type = 'text/css'; if (style.styleSheet) { // IE style.styleSheet.cssText = code; } else { // Other browsers style.innerHTML = code; } document.getElementsByTagName("head")[0].appendChild( style ); } // INJECT THE CSS INTO FUNCTION // Write the css as you normally would... but treat it as strings and concatenate for multilines insertCss( "#injection {color :red; font-size: 30px;}" + "body {background-color: lightblue;}" )