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


当前回答

这是我在最后一个样式表列表的末尾添加css规则的解决方案:

var css = new function()
{
    function addStyleSheet()
    {
        let head = document.head;
        let style = document.createElement("style");

        head.appendChild(style);
    }

    this.insert = function(rule)
    {
        if(document.styleSheets.length == 0) { addStyleSheet(); }

        let sheet = document.styleSheets[document.styleSheets.length - 1];
        let rules = sheet.rules;

        sheet.insertRule(rule, rules.length);
    }
}

css.insert("body { background-color: red }");

其他回答

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

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

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

下面是我的通用函数,它参数化了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);
    }
}

您可以逐个元素添加类或样式属性。

例如:

<a name="myelement" onclick="this.style.color='#FF0';">text</a>

你可以这样做。背景,this.style。字体大小等。你也可以使用同样的方法应用一个样式

this.className='classname';

如果你想在javascript函数中做到这一点,你可以使用getElementByID而不是'this'。

这个简单的例子在html头部添加<style>

var sheet = document.createElement('style');
sheet.innerHTML = "table th{padding-bottom: 0 !important;padding-top: 0 !important;}\n"
+ "table ul {    margin-top: 0 !important;    margin-bottom: 0 !important;}\n"
+ "table td{padding-bottom: 0 !important;padding-top: 0 !important;}\n"
+ ".messages.error{display:none !important;}\n"
+ ".messages.status{display:none !important;} ";

document.body.appendChild(sheet); // append in body
document.head.appendChild(sheet); // append in head

动态样式——用JavaScript操作CSS

我总是忘记如何添加一个类的HTML元素,这个SO出现在谷歌早期,但没有人添加这样做的现代方式,所以在这里。

要添加一个CSS样式,你可以选择元素并调用.classList.add(<className>)

例如: document.querySelector .classList.add(“#主要”)(“bg-primary”);

你可能还需要删除其他与你所添加的类冲突的类。 document.querySelector .classList.remove(“#主要”)(“bg-secondary”);

就是这样。运行示例,您将看到setInterval()方法每3秒添加&删除一次样式。

let useSecondary = false; setInterval(changeBgColor, 3000); function changeBgColor(){ if (useSecondary){ document.querySelector("#main").classList.remove("bg-primary"); document.querySelector("#main").classList.add("bg-secondary"); } else{ document.querySelector("#main").classList.remove("bg-secondary"); document.querySelector("#main").classList.add("bg-primary"); } useSecondary = !useSecondary; } * { transition: all 0.5s ease-in-out; } .bg-primary { background-color: green; } .bg-secondary{ background-color: yellow; } <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width"> <title>JS Bin</title> </head> <body> <div > <div id="main" > Example text has background color changed every 3 seconds by adding / removing CSS styles. </div> </div> </body> </html>