classList

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

1 add -remove

  1. js jquery
  2. add() addClass()
  3. remove() removeClass()
  1. <p id="app">hello world</p>
  2. <button id="btn">移除Class</button>
  3. var app = document.getElementById("app")
  4. var btn = document.getElementById("btn")
  5. app.onclick=function(){
  6. this.classList.add("current")
  7. }
  8. btn.onclick = function(){
  9. app.classList.remove("current")
  10. }

2 toggle - contains

  1. js jquery
  2. toggle toggleClass()
  3. contains hasClass() 判断是否包含某个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. }