ClassList是一個物件,會返回一個 DOMTokenList,裡面包含此元素的類名列表
常見方法:
add():添加一個或多個類,如果此類已經加過就不會再添加
EX:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Hi</title>
<style>
.mystyle {
width: 300px;
height: 50px;
background-color: blue;
color: white;
font-size: 25px;
}
</style>
</head>
<body>
<button onclick="myFunction()">點擊添加 class</button>
<div id="Hi">
Hi!!
</div>
<script>
function myFunction() {
document.getElementById("Hi").classList.add("mystyle");
}
</script>
</body>
</html>
remove():移除一個或多個類名,但如果此類已被移除也會報錯
EX:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Hi</title>
<style>
.mystyle {
width: 300px;
height: 50px;
background-color: blue;
color: white;
font-size: 25px;
}
</style>
</head>
<body>
<button onclick="myFunction()">點擊移除 class</button>
<div id="Hi" class="mystyle">
Hi!!
</div>
<script>
function myFunction() {
document.getElementById("Hi").classList.remove("mystyle");
}
</script>
</body>
</html>
toggle():切換class,如果此class已經在了,就拿走它;如果還沒加上就加上它。
EX:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Hi</title>
<style>
.mystyle {
width: 300px;
height: 50px;
background-color: blue;
color: white;
font-size: 25px;
}
</style>
</head>
<body>
<button onclick="myFunction()">點擊增減 class</button>
<div id="Hi" class="mystyle">
Hi!!
</div>
<script>
function myFunction() {
document.getElementById("Hi").classList.toggle("mystyle");
}
</script>
</body>
</html>
我們用length屬性取用一個ClassList的長度
參考文章:
Runoob HTML DOM classList 属性