11_DOM控制类.html 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  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. color: #fff;
  13. font-size: 20px;
  14. text-align: center;
  15. line-height: 200px;
  16. } */
  17. .active{
  18. width: 200px;
  19. height: 200px;
  20. background-color: red;
  21. color: #fff;
  22. font-size: 20px;
  23. text-align: center;
  24. line-height: 200px;
  25. }
  26. .div1{
  27. font-weight: bold;
  28. }
  29. </style>
  30. </head>
  31. <body>
  32. <div id="box" class="div1">
  33. hello world
  34. </div>
  35. <button id="add-btn">添加类名</button>
  36. <button id="remove-btn">删除类名</button>
  37. <script>
  38. var oBox = document.getElementById("box");
  39. var addBtn = document.getElementById("add-btn");
  40. var removeBtn = document.getElementById("remove-btn");
  41. // 通过js控制类名
  42. addBtn.onclick = function(){
  43. // className 可以控制标签的class 的值 只能实现覆盖效果
  44. // 设置标签的类名 通过className 赋值是一个覆盖 覆盖原有class 里面的值
  45. // oBox.className = "active";
  46. // 获取标签的类名
  47. // console.log(oBox.className);
  48. // 在原有类名基础上新增类名
  49. // 利用字符串拼接实现
  50. // oBox.className = oBox.className + " active";
  51. // 利用classList 实现 新增类名 在class 最后新增一个类名
  52. oBox.classList.add("active");
  53. }
  54. removeBtn.onclick = function(){
  55. // 利用classList 实现 删除类名
  56. oBox.classList.remove("active");
  57. }
  58. // oBox.style.color = "red";
  59. // oBox.styel.width = "200px";
  60. // .
  61. // .
  62. // .
  63. // .
  64. </script>
  65. </body>
  66. </html>