我知道我们可以做很多事情,例如更改元素的当前样式或更改其文本等。但是,我们如何使用 jQuery 更改类的名称?
例如,下面的 CSS 文件有两种不同的样式:
.roundedCorners {
/* code for roundedCorners */
}
.NotSoRoundedCorners {
/* code for NotSoRoundedCorners */
}
按钮看起来像:
<input type="submit" class="NotSoRoundedCorners" value="Turn me on!" />
我知道我们可以使用像这样的简单 jQuery 片段直接更改它的样式:
$('.closer').css({'visibility': 'hidden'}, 1000); // ETC.
但是,如果一个元素有很多样式要更改怎么办。为什么不直接在 CSS 文件中定义 2 个样式,当我们需要更改样式时,只需将元素的 Class 名称更改为另一种样式即可?
最佳答案
您应该调用 jQuery 的 .toggleClass()
help方法。
使用它,您可以显式地删除和添加一个类到节点,而其他类保持不变。
$('.closer').toggleClass('roundedCorners NotSoRoundedCornders');
这里的许多人建议使用 .attr()
,但这会替换整个 className
属性,因此会覆盖/删除任何给定的 css 类。我不认为这是要走的路。
关于javascript - 在 jQuery 中更改类名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5455437/