JavaScript 如何切换元素的类
切换类意味着如果没有分配给元素的类名,则可以通过使用 toggle() 或者通过使用 DOMTokenList 对象的 contains()、add()、remove() 方法来动态分配一个类名,或者如果已经存在某个特定的类,则可以通过使用 toggle() 方法动态地删除该类。
正在使用的HTML元素的属性:
- classList: 该属性将元素的类名作为 DOMTokenList 对象返回。这个对象有一些众所周知的方法,包括 contains()、add()、remove() 和 toggle()。
- contains(): 该方法返回一个布尔值,指示特定的类名是否存在。
- add(): 该方法用于向元素添加一个或多个类名。
- remove(): 该方法用于从元素中删除一个或多个类名。
- toggle(): 该方法属于 DOMTokenList 对象,用于在类之间进行切换。
方法1:使用 toggle() 方法: 让我们首先制作一个包括段落标签和按钮标签的HTML文件模板。然后为要切换的类应用一些样式。在我们的示例中,类名是“paragraphClass”,按钮的ID是“Button”。 现在,让我们编写切换类的脚本。以下是要写在HTML页面的<head>中的脚本。在这种方法中,我们将使用 toggle() 函数来切换类名。
示例: 让我们通过结合上述所有概念来进行工作示例。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Geeks for Geeks</title>
<style>
.paragraphClass {
font-size: 30px;
color: red;
}
#Button {
margin-top: 15px;
}
</style>
<script>
function myFunc() {
var para = document.getElementById("p");
para.classList.toggle("paragraphClass");
}
</script>
</head>
<body>
<p id="p">
Click on the button to toggle
between the class to see the
effects
</p>
<button id="Button" onclick="myFunc()">
Click Me
</button>
</body>
</html>
输出:

方法2:使用contains()、add()和remove()方法: 首先,让我们创建一个包含段落标签和按钮标签的HTML文件模板。之后,让我们为要切换的类应用一些样式。在我们的示例中,类名是“paragraphClass”,按钮的ID是“Button”。
现在,让我们编写切换类的脚本。下面是脚本,它将写在html页面的<head>中。在这个方法中,我们将使用contains()、add()和remove()方法来切换类名。这里的技巧在于,我们将使用contains()方法检查特定类是否存在,然后分别使用add()或remove()方法从元素中添加或删除类名。
示例:让我们通过结合上面描述的所有概念来了解工作示例。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Geeks for Geeks</title>
<style>
.paragraphClass {
font-size: 30px;
color: red;
}
#Button {
margin-top: 15px;
}
</style>
<script>
function myFunc() {
var para = document.getElementById("p");
if(para.classList.contains("paragraphClass")) {
para.classList.remove("paragraphClass");
}
else {
para.classList.add("paragraphClass");
}
}
</script>
</head>
<body>
<p id="p">
Click on the button to toggle
between the class to see the
effects
</p>
<button id="Button" onclick="myFunc()">
Click Me
</button>
</body>
</html>
输出:

极客教程