classList.add() 添加样式

classList.remove() 移除样式

eg: Video_2020-11-24_180948.wmv (87.09KB)

Code:

  1. <style>
  2. .current{
  3. color: red;
  4. }
  5. </style>
  6. <body>
  7. <p id="app">hello world</p>
  8. <button id="btn">移除class</button>
  9. <script>
  10. var app =document.getElementById("app");
  11. var btn =document.getElementById("btn");
  12. app.onclick = function(){
  13. this.classList.add("current")
  14. }
  15. btn.onclick = function(){
  16. app.classList.remove("current")
  17. }
  18. </script>
  19. </body>

classList.toggle() 切换 样式添加/样式移除

效果: Video_2020-11-24_181632.wmv (98.14KB)

Code:

  1. <style>
  2. .current{
  3. color: red;
  4. }
  5. </style>
  6. <body>
  7. <p id="app">hello world</p>
  8. <script>
  9. var app = document.getElementById("app");
  10. app.onclick =function(){
  11. this.classList.toggle("current")
  12. }
  13. </script>
  14. </body>

classList.contains() 判断是否包含某个样式 返回值为 true / false

eg:

  1. <style>
  2. .current{
  3. color: red;
  4. }
  5. </style>
  6. <body>
  7. <p id="app">hello world</p>
  8. <script>
  9. var app = document.getElementById("app");
  10. app.onclick =function(){
  11. this.classList.toggle("current")
  12. console.log(this.classList.contains("current"))
  13. }
  14. </script>
  15. </body>