一、getComputedStyle 介绍
getComputedStyle是一个可以获取当前元素所有最终使用的CSS属性值。返回的是一个CSS样式声明对象([object CSSStyleDeclaration]),<mark>只读</mark>。
getComputedStyle() gives the final used values of all the CSS properties of an element.
举个栗子
// window.getComputedStyle("元素", "伪类");
var dom = document.getElementById("test"),
style = window.getComputedStyle(dom , ":after");
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>getComputedStyle 学习</title>
<style type="text/css">
#div1{
width: 200px;
height: 200px;
background-color: red;
}
</style>
<script type="text/javascript">
window.onload = function () {
var oDiv = document.getElementById('div1');
alert('width:' + getComputedStyle(oDiv, null).backgroundColor);
}
</script>
</head>
<body>
<div id="div1"></div>
</body>
</html>
二、getComputedStyle与style的区别
我们使用element.style也可以获取元素的CSS样式声明对象,但是其与getComputedStyle方法还有有一些差异的(只读与可写)。
1、正如上面提到的getComputedStyle方法是只读的,只能获取样式,不能设置;而element.style能读能写,能屈能伸。
2、获取的对象范围getComputedStyle方法获取的是最终应用在元素上的所有CSS属性对象(即使没有CSS代码,也会把默认的祖宗八代都显示出来);
而element.style只能获取元素style属性中的CSS样式。因此对于一个光秃秃的元素<p>,getComputedStyle方法返回对象中length属性值
(如果有)就是190+, 而element.style就是0。