获取计算后的样式
<head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <style> .box { width: 100px; height: 100px; color: red; background-color: skyblue; } </style></head><body> <div id="box" class="box"></div> <script> var box = document.getElementById('box'); // console.log(box.style.width) // getComputedStyle 获取计算后样式 // var cssObj = window.getComputedStyle(box) // console.log(cssObj.display) // console.log(cssObj.backgroundColor) // css中的带-的属性 我们在js中要去掉- 并把后面的首字母转大写 // console.log(cssObj['background-color']) // IE中不支持getComputedStyle 但是有自己的属性 currentStyle // 一个对象的属性值如果是函数 那么我们管它叫方法 // console.log(box.currentStyle.backgroundColor); console.log(window.navigator) // 解决兼容性问题 // 因为我们不知道我们所写的代码将来会被运行在哪里 所以代码如何写? // 所以我们就要解决这样的问题 // 我们通常会封装一个函数 用于解决 // function getCss(yuansu, shuxing) { // if (window.navigator.userAgent.indexOf("IE") != -1) { // return yuansu.currentStyle[shuxing] // } else { // return window.getComputedStyle(yuansu)[shuxing]; // } // } function getCss(yuansu, shuxing) { // 能力检测 if (window.getComputedStyle) { return window.getComputedStyle(yuansu)[shuxing] } else { return yuansu.currentStyle[shuxing] } } var width = getCss(box, 'width'); console.log(width) </script></body></html>