05.读取元素的样式.html 4.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  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: 100px;
  11. height: 100px;
  12. background-color: yellow;
  13. }
  14. ;
  15. </style>
  16. <script>
  17. window.onload = function () {
  18. //点击按钮以后读取box1的样式
  19. var box1 = document.getElementById("box1");
  20. var btn01 = document.getElementById("btn01");
  21. btn01.onclick = function () {
  22. //读取box1的宽度
  23. /**
  24. * 获取元素的当前显示的样式
  25. * 语法:
  26. * 元素.currentStyle.样式名
  27. * 它可以用来读取当前元素正在显示的样式
  28. * 如果当前元素没有设置该样式,则获取它的默认值
  29. * currentStyle只有IE浏览器支持,其他的浏览器都不支持
  30. */
  31. //alert(box1.currentStyle.width);
  32. //alert(box1.currentStyle.backgroundColor);
  33. /**
  34. * 在其他浏览器中可以使用
  35. * getComputedStyle()这个方法来获取元素当前的样式
  36. * 这个方法是window的方法,可以直接使用
  37. * 需要两个参数:
  38. * 第一个:要获取样式的元素
  39. * 第二个:可以传递一个伪元素,一般都传null
  40. *
  41. * 该方法会返回一个对象,对象中封装了当前元素对应的样式
  42. * 可以通过“对象.样式名”来读取样式
  43. * 如果获取的样式没有设置,则会获取到真实的值,而不是默认值
  44. * 比如:没有设置width,他不会获取到auto,而是一个长度
  45. *
  46. * 但是该方法不支持IE8及以下的浏览器
  47. * 通过currentStyle和getComputedStyle读取到的样式都是只读的,
  48. * 不能修改,如果要修改必须通过style属性
  49. */
  50. // var obj = getComputedStyle(box1,null);
  51. // alert(obj.width);
  52. //或者直接写成下面的格式
  53. // alert(getComputedStyle(box1,null).width);
  54. //这是正常浏览器的方式
  55. // alert(getComputedStyle(box1,null).backgroundColor);
  56. //IE8的方式
  57. // alert(box1.currentStyle.backgroundColor);
  58. // alert(getStyle(box1,"width"));
  59. var w = getStyle(box1, "width");
  60. alert(w);
  61. };
  62. };
  63. /**
  64. * 定义一个函数,用来获取指定元素的当前的样式
  65. * 参数:
  66. * obj:要获取样式的元素
  67. * name:要获取的样式名
  68. */
  69. function getStyle(obj, name) {
  70. if (window.getComputedStyle) {
  71. //正常浏览器的方式,具有getComputedStyle()方法
  72. return getComputedStyle(obj, null)[name];
  73. } else {
  74. //IE8的方式,没有getComputedStyle()方法
  75. return obj.currentStyle[name];
  76. };
  77. //也可以换一种写法,不过建议使用上面的写法
  78. // if(obj.currentStyle){
  79. // return obj.currentStyle[name];
  80. // }else{
  81. // return getComputedStyle(obj,null)[name];
  82. // };
  83. //推荐使用第一种方式,更加清晰
  84. // return window.getComputedStyle?getComputedStyle(obj, null)[name]:obj.currentStyle[name];
  85. };
  86. </script>
  87. </head>
  88. <body>
  89. <button id="btn01">点我一下</button>
  90. <br /><br />
  91. <div id="box1" style="width: 200px;border-color: red;"></div>
  92. </body>
  93. </html>