简体   繁体   English

快速更改元素的CSS类

[英]Change elements' CSS class on the fly

On a page using jQuery, if I want to to change all classes from 在使用jQuery的页面上,如果我想更改所有类

col-lg-3 form-group

to

col-lg-8 form-group

How can I do that? 我怎样才能做到这一点?

$('.col-lg-3.form-group').toggleClass('col-lg-3 col-lg-8');

.toggleClass just toggles the classnames based off the list given. .toggleClass只是根据给定的列表切换类名。

So if you run it again it will be back to the original. 因此,如果再次运行它,它将恢复为原始状态。

除了Tuvia和jlemm45的答案,您还可以执行以下操作:

$('.col-lg-3.form-group').switchClass( "col-lg-3", "col-lg-8", 0)

You can use removeClass() and addClass() . 您可以使用removeClass()addClass() The below code will search for elements which have both .col-lg-3 and .form-group as class , and it will remove the col-lg-3 class for those elements and add col-lg-8 class. 在下面的代码将搜索具有两个元件.col-lg-3.form-group如类,并且它将删除 col-lg-3类的那些元件,并添加 col-lg-8类。

$('.col-lg-3.form-group').removeClass('col-lg-3').addClass('col-lg-8');

Sample Demo 样本演示

 $( ".form-group.col-lg-3" ).removeClass( "col-lg-3").addClass('col-lg-8'); 
 .form-group { color: blue; } .col-lg-3 { text-decoration: underline; } .col-lg-8{ font-size:50px; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <h3 class="form-group col-lg-3">text</h3> <h3 class="form-group">text</h3> <h3 class="col-lg-3">text</h3> <h3 class="form-group col-lg-3">text</h3> 

Simple way to do it would be like below.. 简单的方法如下所示。

$('.col-lg-3.form-group').removeClass('col-lg-3').addClass('col-lg-8')

Removes the col-lg-3 class and adds col-lg-8 to all the elements which has the combinations of both the classes col-lg-3 and form-group in its class attribute. 除去col-lg-3类,并将col-lg-8到所有在其class属性中具有col-lg-3form-group组合的元素。

有几种不同的方法,但是这是我要做的。

$('.form-group').removeClass('col-lg-3').addClass('col-lg-8');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM