要删除所有 CSS 类,我们可以使用 jQuery 方法或者 JavaScript 属性。
.removeAttr() 方法
.removeAttr() 方法使用 removeAttribute() JavaScript 函数,但它可以直接在 jQuery 对象上调用。
$("#element").removeAttr('class');
例子:
<!DOCTYPE html>
<html>
<head>
<title>文档的标题</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.0/jquery.min.js"></script>
</head>
<body>
<a href="#">Link </a>
<button type="button" class="remove-attr"> Remove Link</button>
<script>
$(document).ready(function() {
$(".remove-attr").click(function() {
$("a").removeAttr("href");
});
});
</script>
</body>
</html>
.attr() 方法
如果我们将 class 属性设置为空,则会从元素中删除所有类,但也会在 DOM 上留下一个空的 class 属性。
.attr() jQuery 方法获取集合中第一个元素的属性值。
$("#element").attr('class', '');
例子:
<!DOCTYPE html>
<html>
<head>
<title>文档的标题</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.0/jquery.min.js"></script>
</head>
<body>
<button type="button" class="add-attr">Select Checkbox</button>
<input type="checkbox">
<script>
$(document).ready(function() {
$(".add-attr").click(function() {
$('input[type="checkbox"]').attr("checked", "checked");
alert('Checked!');
});
});
</script>
</body>
</html>
removeClass() 方法
删除所有项的类最常用的方法是 removeClass() jQuery 方法。
此方法从匹配元素集中的每个元素中删除单个、多个或者所有类。
如果将类名指定为参数,则只会从匹配元素集中删除该类。
如果参数中未定义类名,则将删除所有类。
$("#element").removeClass();
例子 :
<!DOCTYPE html>
<html>
<head>
<title>文档的标题</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.0/jquery.min.js"></script>
<style>
.green {
color: green;
}
.blue {
color: blue;
}
</style>
</head>
<body>
<p class="green">经历过风雨,才懂得阳光的温暖。</p>
<p class="blue">生活终归还得继续。</p>
<button id="buttonId">删除类</button>
<script>
$(document).ready(function() {
$("#buttonId").click(function() {
$("p").removeClass();
});
});
</script>
</body>
</html>
JavaScript className 属性
我们只能使用纯 JavaScript。
将 className 属性设置为空,这会将 class 属性的值设置为 null:
document.getElementById('element').className = '';
例子:
<!DOCTYPE html>
<html>
<head>
<title>文档的标题</title>
<style>
.addStyle {
width: 500px;
background-color: yellow;
color: red;
text-align: center;
font-size: 20px;
}
</style>
</head>
<body>
<div id="divId">
<h1>onitroad</h1>
</div>
<button onclick="myFunction()">Click on button</button>
<script>
function myFunction() {
document.getElementById("divId").className = "addStyle";
}
</script>
</body>
</html>
className 属性返回元素的类名。
日期:2020-06-02 22:16:24 来源:oir作者:oir
