代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
* {
margin: 0;
padding: 0;
}
#box {
width: 200px;
height: 200px;
background: coral;
}
#box2 {
width: 100px;
height: 100px;
background: peru;
}
#box3 {
width: 111px;
height: 111px;
background: forestgreen;
}
</style>
</head>
<body>
<div id="box" ></div>
<div id="box2" ></div>
<div id="box3" style="color:#000;"></div>
<script>
/*
获取非行间样式方法:
兼容:
标准【谷歌,火狐,360...】:getComputedStyle
格式: getComputedStyle(元素).样式属性
IE: currentStyle
格式: 元素.currentStyle.样式属性
*/
var box = document.getElementById('box');
var box2 = document.getElementById('box2');
var box3 = document.getElementById('box3');
// console.log(getComputedStyle(box).height);
// console.log(box.currentStyle.background);
// 兼容判断
function fn(ele,attr) {
if (window.getComputedStyle) { // 标准浏览器
return getComputedStyle(ele)[attr];
} else { // ie浏览器
return ele.currentStyle[attr];
}
}
box.innerHTML = fn(box,'width');
box2.innerHTML = fn(box2,'height');
box3.innerHTML = fn(box3,'background')
/*
1.找到反复执行的代码块,用一个函数外壳将其套起来
2.在代码块中找到有可能变化的地方,提成未知数(形参)
3.调用函数,并且传实参。
*/
// console.log(getComputedStyle(box3).color)
</script>
</body>
</html>