04.使用DOM操作CSS.html 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <meta http-equiv="X-UA-Compatible" content="IE=edge">
  6. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  7. <title>Document</title>
  8. <style>
  9. #box1{
  10. width: 200px;
  11. height: 200px;
  12. background-color: red;
  13. };
  14. </style>
  15. <script>
  16. window.onload = function(){
  17. /**
  18. * 点击按钮以后,修改box1的大小
  19. */
  20. //获取box1
  21. var box1 = document.getElementById("box1");
  22. //为按钮绑定单击响应函数
  23. var btn01 = document.getElementById("btn01");
  24. btn01.onclick = function(){
  25. // alert("hello");
  26. //修改box1的宽度
  27. /**
  28. * 通过JS修改元素的样式:
  29. * 语法:元素.style.样式名 = 样式值
  30. *
  31. * 注意:如果CSS的样式名中含有“-”,
  32. * 这种名称在JS中是不合法的,比如background-color
  33. * 需要将这种样式名修改为驼峰命名法:
  34. * 去掉“-”,然后将“-”后的字母大写
  35. * 比如:如果名称为border-top-width,则需要修改为:
  36. * borderTopWidth
  37. *
  38. * 我们通过style属性设置的样式都是内联样式,
  39. * 而内联样式有较高的优先级,所以通过JS修改的样式往往会立即显示
  40. *
  41. * 但是,如果在样式中写了!important,则此时样式会有最高的优先级,
  42. * 即使通过JS也不能覆盖该样式,此时将会导致JS修改样式失效
  43. * 所以尽量不要为样式添加!important
  44. *
  45. *
  46. */
  47. box1.style.width = "300px";
  48. box1.style.height = "300px";
  49. box1.style.backgroundColor = "yellow";
  50. };
  51. //点击按钮2以后,读取元素的样式
  52. var btn02 = document.getElementById("btn02");
  53. btn02.onclick = function(){
  54. //读取box1的样式
  55. /**
  56. * 语法:
  57. * 元素.样式名.style.样式名
  58. *
  59. * 通过style属性设置和读取的都是内联样式
  60. * 无法读取样式表中的样式
  61. */
  62. alert(box1.style.width);
  63. }
  64. };
  65. </script>
  66. </head>
  67. <body>
  68. <button id="btn01">点我一下</button>
  69. <button id="btn02">再点一下</button>
  70. <br/><br/>
  71. <div id="box1"></div>
  72. </body>
  73. </html>