如何使用 javascript 更改 css 类属性?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/49162654/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 08:27:21  来源:igfitidea点击:

How to change css class property with javascript?

javascripthtmlcss

提问by Dawid G

can someone tell me how can i change css class property by javascript? example:

有人可以告诉我如何通过 javascript 更改 css 类属性吗?例子:

.winner
{
    background-color: white;
}

How can I change value of class winner background-color. When I write: var some = document.querySelector("winner"); I get button with class winner. I want this class not element of html. How can i get it?

如何更改类优胜者背景颜色的值。当我写: var some = document.querySelector("winner"); 我得到与班级优胜者的按钮。我想要这个类不是 html 的元素。我怎么才能得到它?

回答by JCollier

There's a few ways you could do this:

有几种方法可以做到这一点:

On top of your current class in your .css file, you could add another class in there, and then just switch the HTML elements to belong to that new class. You would need to loop through all the elements with that class name and change them to the new name:

在 .css 文件中的当前类之上,您可以在其中添加另一个类,然后只需将 HTML 元素切换为属于该新类。您需要遍历具有该类名的所有元素并将它们更改为新名称:

CSS:

CSS:

.winner
{
    background-color: white;
}

.winnerBlue
{
    background-color: blue;
}

JavaScript:

JavaScript:

var winnerClassElements = document.getElementsByClassName("winner");
for(var i = 0; i < winnerClassElements.length; i++)
{
    document.getElementById(winnerClassElements.item(i)).className = "winnerBlue";
}


You could also add some style elements to your HTML file with this JavaScript code:

您还可以使用以下 JavaScript 代码向 HTML 文件添加一些样式元素:

var editCSS = document.createElement('style')
editCSS.innerHTML = ".winner {background-color: blue;}";
document.body.appendChild(editCSS);


I know you didn't ask for jQuery, but if you already have it included, this is a very simple solution:

我知道你没有要求 jQuery,但如果你已经包含它,这是一个非常简单的解决方案:

$('.winner').css("background-color" , "blue");

回答by Scott Marcus

The way to accomplish this is to either remove the class from being applied or apply another class that overrides the first. The DOM Element classListproperty is the key.

实现这一点的方法是从被应用的类中删除或应用另一个覆盖第一个类的类。DOM 元素classList属性是关键。

document.querySelector("input").addEventListener("click", function(){
  document.querySelector("h1").classList.remove("normal");
  document.querySelector("h1").classList.add("special");  
});
.normal { background-color:purple; }
.special { background-color:yellow; }
<h1 class="normal">Just some text</h1>
<input type="button" value="Click to change style">