classList 属性返回元素的类名,作为 DOMTokenList 对象。该属性用于在元素中添加,移除及切换 CSS 类
5.1 add() — 增加class
<p id="app">hello world</p><button id="btn">移除class</button> <script> var app = document.getElementById("app"); var btn = document.getElementById("btn"); app.onclick = function(){ this.classList.add("current") } </script>
5.2 remove() — 移除class
btn.onclick = function(){ app.classList.remove("current") }
5.3 toggle( ) 切换 contains( ) 判断是否包含某个class
<p id="app">hello world</p>var app = document.getElementById("app")app.onclick = function(){ /* if(this.classList.contains("current")){ this.classList.remove("current") }else{ this.classList.add("current") } */ this.classList.toggle("current")}