源码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>DOM通过class属性设置样式</title>
<style>
.active{
background-color: red;
}
</style>
</head>
<body>
<h1>Hello World</h1>
<h1>Hello World</h1>
<h1>Hello World</h1>
<h1>Hello World</h1>
<h1>Hello World</h1>
<script>
let h1List = document.querySelectorAll("h1");
for(let i in h1List){
h1List[i].onclick = function (){
if (this.className === "active"){
this.className = ""
}else {
this.className = "active"
}
}
}
</script>
</body>
</html>