14_控制类.html 1016 B

12345678910111213141516171819202122232425262728293031323334353637383940
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  6. <title>Document</title>
  7. <style>
  8. .box{
  9. width: 200px;
  10. height: 200px;
  11. background-color: red;
  12. }
  13. .active{
  14. background-color: blue;
  15. }
  16. .div1{
  17. font-size: 50px;
  18. }
  19. </style>
  20. </head>
  21. <body>
  22. <div class="box div1">hello</div>
  23. <button id="btn">切换类名</button>
  24. <script>
  25. // 获取元素
  26. var box = document.querySelector(".box");
  27. var btn = document.querySelector("#btn");
  28. // 绑定事件
  29. btn.onclick = function(){
  30. // 操作类 classList 方法
  31. // add()方法可以添加类名 只是在基础上添加类名 不会覆盖之前的类名
  32. // box.classList.add("active");
  33. // remove()
  34. // box.classList.remove("div1");
  35. }
  36. </script>
  37. </body>
  38. </html>