获取计算后的样式

  1. <head>
  2. <meta charset="UTF-8">
  3. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  4. <title>Document</title>
  5. <style>
  6. .box {
  7. width: 100px;
  8. height: 100px;
  9. color: red;
  10. background-color: skyblue;
  11. }
  12. </style>
  13. </head>
  14. <body>
  15. <div id="box" class="box"></div>
  16. <script>
  17. var box = document.getElementById('box');
  18. // console.log(box.style.width)
  19. // getComputedStyle 获取计算后样式
  20. // var cssObj = window.getComputedStyle(box)
  21. // console.log(cssObj.display)
  22. // console.log(cssObj.backgroundColor) // css中的带-的属性 我们在js中要去掉- 并把后面的首字母转大写
  23. // console.log(cssObj['background-color'])
  24. // IE中不支持getComputedStyle 但是有自己的属性 currentStyle
  25. // 一个对象的属性值如果是函数 那么我们管它叫方法
  26. // console.log(box.currentStyle.backgroundColor);
  27. console.log(window.navigator)
  28. // 解决兼容性问题
  29. // 因为我们不知道我们所写的代码将来会被运行在哪里 所以代码如何写?
  30. // 所以我们就要解决这样的问题
  31. // 我们通常会封装一个函数 用于解决
  32. // function getCss(yuansu, shuxing) {
  33. // if (window.navigator.userAgent.indexOf("IE") != -1) {
  34. // return yuansu.currentStyle[shuxing]
  35. // } else {
  36. // return window.getComputedStyle(yuansu)[shuxing];
  37. // }
  38. // }
  39. function getCss(yuansu, shuxing) {
  40. // 能力检测
  41. if (window.getComputedStyle) {
  42. return window.getComputedStyle(yuansu)[shuxing]
  43. } else {
  44. return yuansu.currentStyle[shuxing]
  45. }
  46. }
  47. var width = getCss(box, 'width');
  48. console.log(width)
  49. </script>
  50. </body>
  51. </html>