获取任意样式的值的函数的封装
<!DOCTYPE html>
<html>
<head>
<meta cahrset="utf-8">
<title>获取任意样式的值的函数的封装</title>
<style>
*{
margin: 0;
padding: 0;
}
#box{
width: 100px;
height: 100px;
background-color: lime;
position: absolute;
}
</style>
</head>
<body>
<div id="box"></div>
<script>
let box = document.querySelector('#box')
// 获取任意样式属性的值
function getStyle(element,attr){
// 如果这个函数存在,就调用这个函数
if(window.getComputedStyle){
// 获取计算后的样式,即在运行中生效的样式
return window.getComputedStyle(element,null)[attr]
}else{
// IE8和以下版本使用这个函数获取计算后的样式
return element.currentStyle[attr]
}
}
// 获取宽度
console.log(getStyle(box,'width'))
// 获取背景色
console.log(getStyle(box,'backgroundColor'))
</script>
</body>
</html>
IE8