javascript - 有什么方法可以更改在浏览器中注册的 CSS 类

标签 javascript html css

我用一个简单的例子来解释这个问题。 我有以下 html 页面。很简单。

有一个名为 TestDiv 的 CSS 类和两个 javascript 函数。

  1. addDiv 创建新的 div 并通过单击按钮“添加新的 div” 将其附加到页面。
  2. setBlue 是我想更改具有 TestDiv 类的 div 颜色的函数,我不知道如何

您可以看到我在 setBlue 函数中编写了一些代码来更改当前生成的 Div。但我不知道如何更改类以影响之后由 addDiv 函数生成的新 div。

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <style>
        .TestDiv {
            color:red;
        }
    </style>
    <script>
        function addDiv() {
            var newDiv = document.createElement("div")
            newDiv.className = "TestDiv";
            newDiv.innerHTML = "test";
            document.getElementById("firstDiv").insertBefore(newDiv);
        }
        function setBlue() {

            var currentDivList=document.getElementsByClassName("TestDiv");
            for(var i=0;i<currentDivList.length;i++){
                currentDivList[i].style.color = "blue";
            }
            // What i can write here to change the TestDiv css class
            // And after that, new (div)s will generate by new color(changed css class)
        }
    </script>
</head>
<body>
    <div id="firstDiv" class="TestDiv">
        test
    </div>

    <input type="button" value="add new div" onclick="addDiv();"/>
    <input type="button" value="change color to blue" onclick="setBlue();"/>
</body>
</html>

最佳答案

我不建议即时添加或修改 CSS 规则,但有几种解决方案:

  • 修改原来的CSS规则

    <style id="myStyle">
        .TestDiv {
            color:red;
        }
    </style>
    
    ...
    
    var myStyle = document.getElementById("myStyle");
    myStyle.sheet.cssRules.item(0).cssText = ".TestDiv { color: blue }";
    

    (我必须为样式标签分配一个 ID,否则我无法让它在 jsFiddle 环境中工作。使用 document.styleSheets[0] 应该同样可行。)

  • 将 CSS 规则添加到新创建的样式表(感谢 pawel !)

    var style = document.createElement('style');
    document.head.appendChild(style);
    style.sheet.addRule(".TestDiv", "color: blue");
    
  • 将原始 CSS 文本添加到新创建的样式表: → jsFiddle

    var sheet = document.createElement('style')
    sheet.innerHTML = ".TestDiv { color: blue }";
    document.body.appendChild(sheet);
    

关于javascript - 有什么方法可以更改在浏览器中注册的 CSS 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19635582/

相关文章:

JavaScript 将函数参数与现有变量相结合

javascript - 表行循环计算

javascript - Amazon S3 签名不匹配 - AWS 开发工具包 Java

css - 您可以使用 HTML5 详细信息标签在右侧而不是在 <li> 下方打开一个描述框吗?

jquery - box-shadow 仅显示在图像的左侧

javascript - JQuery 鼠标事件 : How to trigger a callback if the element moves?

javascript - 在 JavaScript 中连接字符串的问题

jQuery 悬停效果 - 需要帮助改进此代码

css - HTML5 页脚 - 我无法删除的边距

javascript - 如何获取图像的高度和宽度javascript