0%

toggle

DOMTokenList.toggle()

DOMTokenList接口的toggle()方法从列表中删除一个给定的标记并返回false,如果标记不存在,则添加并且函数返回true

tokenList.toggle(token,force);

参数:

token:标记列表中你想探查并切换的DOMSring

force(可选):Boolean值,设置后会将方法变成单向操作,如果设置为false,则会删除标记列表中匹配的给定标记,且不会再添加,如设置为true,则将在标记中添加给定标记,且不会再度删除

返回值:

为布尔值

eg

HTML

1
<span class="a b">classList is 'a b'</span>

JavaScript

1
2
3
4
5
6
7
8
9
10
var span = document.querySelector("span");
var classes = span.classList;
span.onclick = function() {
var result = classes.toggle("c");
if(result) {
span.textContent = "'c' added; classList is now '" + classes + "'.";
} else {
span.textContent = "'c' removed; classList is now '" + classes + "'.";
}
}