getComputedStyle()方法返回的是一个CSS样式声明对象--CSSStyleDeclaration对象(与style属性的类型相同),包含当前元素所有最终使用的CSS属性值;
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
<style>
#myDiv {
background-color: #FFF;
width: 200px;
height: 200px;
}
</style>
</head>
<body>
<div id="myDiv" style="background-color: red; border: 1px solid #333;"></div>
</body>
<script>
var myDiv = document.getElementById('myDiv');
var computedStyle = document.defaultView.getComputedStyle(myDiv, null);
console.log(computedStyle.backgroundColor);//rgb(255, 0, 0)
console.log(computedStyle.width);//200px
console.log(computedStyle.height);//200px
console.log(parseFloat(computedStyle.border));//
console.log(computedStyle.border);//1px solid rgb(51, 51, 51)(chrome下)
//NaN(Firefox下)
//1px solid rgb(51, 51, 51)(Opera下)
</script>
</html>
IE不支持getComputedStyle()方法,取而代之的是
IE浏览器的一个属性currentStyle;
var myDiv = document.getElementById('myDiv');
var computedStyle = myDiv.currentStyle;
console.log(computedStyle.backgroundColor);
console.log(computedStyle.width);
console.log(computedStyle.height);
console.log(computedStyle.border);//undefined
造成border差异原因:
border: 1px solid #333;是一个复合属性,浏览器在解析时把border解释为:borderleftwidth: 200px; borderleftcolor: #333; borderleftstyle: solid; ...一个div有四条边,每条边的样式(如宽度,颜色等)都可能不同,所以在不同的浏览器下输出结果会不一致;
延伸:与style.css区别
getComputedStyle()获取完整样式,而style.css仅能获得内联样式中的部分属性,无法获得层叠或继承来的外部属性;
使用注意点:
1、仅能设置内联样式中的css属性, css属性名(class-name)都要去横线变驼峰命名(className);
2、无论是获取/设置的css属性值必须都是字符串;获取时,要去单位,再计算;修改时,要补单位,再赋值;
声明:本博客的文章除特殊说明外均为原创,转载请注明出处;