1. classList 属性返回元素的类名,作为 DOMTokenList 对象。
  2. 该属性用于在元素中添加,移除及切换 CSS

5.1 add() — 增加class

  1. <p id="app">hello world</p>
  2. <button id="btn">移除class</button>
  3. <script>
  4. var app = document.getElementById("app");
  5. var btn = document.getElementById("btn");
  6. app.onclick = function(){
  7. this.classList.add("current")
  8. }
  9. </script>

5.2 remove() — 移除class

  1. btn.onclick = function(){
  2. app.classList.remove("current")
  3. }

5.3 toggle( ) 切换 contains( ) 判断是否包含某个class

  1. <p id="app">hello world</p>
  2. var app = document.getElementById("app")
  3. app.onclick = function(){
  4. /* if(this.classList.contains("current")){
  5. this.classList.remove("current")
  6. }else{
  7. this.classList.add("current")
  8. } */
  9. this.classList.toggle("current")
  10. }