如何通过 Javascript 更改 css 类样式?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2221160/
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
How to change a css class style through Javascript?
提问by sasori
According to the book that I am reading, it is better to change a css, by class when you are using Javascript for changing css. But how? Can someone give a sample snippet for this?
根据我正在阅读的书,当您使用 Javascript 更改 css 时,最好按类更改 css。但是如何?有人可以为此提供示例片段吗?
回答by Asaph
Suppose you have:
假设你有:
<div id="mydiv" class="oldclass">text</div>
and the following styles:
以及以下样式:
.oldclass { color: blue }
.newclass { background-color: yellow }
You can change the class on mydivin javascript like this:
您可以mydiv像这样在 javascript 中更改类:
document.getElementById('mydiv').className = 'newclass';
After the DOM manipulation you will be left with:
在 DOM 操作之后,您将剩下:
<div id="mydiv" class="newclass">text</div>
If you want to add a new css class without removing the old one, you can append to it:
如果你想添加一个新的 css 类而不删除旧的,你可以附加到它:
document.getElementById('mydiv').className += ' newClass';
This will result in:
这将导致:
<div id="mydiv" class="oldclass newclass">text</div>
回答by Jan Turoň
Since classListis supported in all major browsersand jQuery drops support for IE<9(in 2.x branch as Stormblack points in the comment), considering this HTML
由于所有主要浏览器都支持classList并且jQuery 放弃了对 IE<9 的支持(在 2.x 分支中作为 Stormblack 点在评论中),考虑到这个 HTML
<div id="mydiv" class="oldclass">text</div>
you can comfortably use this syntax:
您可以轻松地使用以下语法:
document.getElementById('mydiv').classList.add("newClass");
This will also result in:
这也会导致:
<div id="mydiv" class="oldclass newclass">text</div>
plus you can also use remove, toggle, containsmethods.
此外,您还可以使用remove、toggle、contains方法。
回答by Andy Shellam
I'd highly recommend jQuery. It then becomes as simple as:
我强烈推荐jQuery。然后它变得如此简单:
$('#mydiv').addClass('newclass');
You don't have to worry about removing the old class then as addClass() will only append to it. You also have removeClass();
您不必担心删除旧类,因为 addClass() 只会附加到它。你也有 removeClass();
The other advantage over the getElementById() method is you can apply it to multiple elements at the same time with a single line of code.
与 getElementById() 方法相比的另一个优点是您可以使用一行代码同时将其应用于多个元素。
$('div').addClass('newclass');
$('.oldclass').addClass('newclass');
The first example will add the class to all DIV elements on the page. The second example will add the new class to all elements that currently have the old class.
第一个示例将类添加到页面上的所有 DIV 元素。第二个示例将新类添加到当前具有旧类的所有元素。
回答by gmoz22
If you want to manipulate the actual CSS classinstead of modifying the DOM elements or using modifier CSS classes, see https://stackoverflow.com/a/50036923/482916.
如果您想操作实际的 CSS 类而不是修改 DOM 元素或使用修饰符 CSS 类,请参阅 https://stackoverflow.com/a/50036923/482916。
回答by nwayve
There are two ways in which this can be accomplished using vanilla javascript. The first is classNameand the second is classList. classNameworks in all browsers but can be unwieldy to work with when modifying an element's class attribute. classListis an easier way to modify an element's class(es).
有两种方法可以使用 vanilla javascript 来完成。第一个是className,第二个是classList。 className适用于所有浏览器,但在修改元素的类属性时可能难以使用。 classList是一种更简单的方法来修改元素的类。
To outright set an element's class attribute, classNameis the way to go, otherwise to modify an element's class(es), it's easier to use classList.
彻底设置元素的类属性,className是要走的路,否则修改元素的类,使用更容易classList。
Initial Html
初始 Html
<div id="ID"></div>
Settingthe class attribute
设置类属性
var div = document.getElementById('ID');
div.className = "foo bar car";
Result:
结果:
<div id="ID" class="foo bar car"></div>
Addinga class
添加班级
div.classList.add("car");// Class already exists, nothing happens
div.classList.add("tar");
Note:There's no need to test if a class exists before adding it. If a class needs to be added, just add it. If it already exists, a duplicate won't be added.
Result:
注意:在添加一个类之前不需要测试它是否存在。如果需要添加一个类,只需添加它。如果它已经存在,则不会添加重复项。
结果:
<div id="ID" class="foo bar car tar"></div>
Removinga class
删除类
div.classList.remove("car");
div.classList.remove("tar");
div.classList.remove("car");// No class of this name exists, nothing happens
Note:Just like add, if a class needs to be removed, remove it. If it's there, it'll be removed, otherwise nothing will happen.
Result:
注意:就像add,如果需要删除一个类,请将其删除。如果它在那里,它将被删除,否则什么都不会发生。
结果:
<div id="ID" class="foo bar"></div>
Checking if a class attribute containsa specific class
检查类属性是否包含特定类
if (div.classList.contains("foo")) {
// Do stuff
}
Togglinga class
切换班级
var classWasAdded = div.classList.toggle("bar"); // "bar" gets removed
// classWasAdded is false since "bar" was removed
classWasAdded = div.classList.toggle("bar"); // "bar" gets added
// classWasAdded is true since "bar" was added
.togglehas a second booleanparameter that, in my opinion, is redundant and isn't worth going over.
.toggle有第二个布尔参数,在我看来,它是多余的,不值得讨论。
For more information on classList, check out MDN. It also covers browser compatibilityif that's a concern, which can be addressed by using Modernizr for detection and a polyfill if needed.
有关更多信息classList,请查看MDN。如果这是一个问题,它还涵盖了浏览器兼容性,这可以通过使用 Modernizr 进行检测并在需要时使用 polyfill 来解决。
回答by knittl
use the classNameproperty:
使用className属性:
document.getElementById('your_element_s_id').className = 'cssClass';
回答by Adir
document.getElementById("my").className = 'myclass';
document.getElementById("my").className = 'myclass';
回答by Juri
You may also be interested in modifying it using jQuery: http://api.jquery.com/category/css/
您可能也有兴趣使用 jQuery 修改它:http: //api.jquery.com/category/css/
回答by chanakya s
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("div").addClass(function(){
return "par" ;
});
});
</script>
<style>
.par {
color: blue;
}
</style>
</head>
<body>
<div class="test">This is a paragraph.</div>
</body>
</html>

