getComputedStyle()方法

getComputedStyle()方法返回的是一个CSS样式声明对象--CSSStyleDeclaration对象(与style属性的类型相同),包含当前元素所有最终使用的CSS属性值。

<!DOCTYPE html>
<html>
<head>
    <title>Computed Styles Example</title>
    <style type="text/css">
        #myDiv {
            background-color: blue;
            width: 100px;
            height: 200px;
        }
    </style>
    <script type="text/javascript">
        function showComputedStyles(){
            var myDiv = document.getElementById("myDiv");
            var computedStyle = document.defaultView.getComputedStyle(myDiv, null);
            alert(computedStyle.backgroundColor);   //"red"
            alert(computedStyle.width);             //"100px"
            alert(computedStyle.height);            //"200px"
            alert(computedStyle.border);            //"1px solid black"
            alert(computedStyle.borderLeftWidth);   //"1px"
            alert(computedStyle.visibility);
        }
    </script>
</head>
<body>
    <div id="myDiv" style="background-color: red; border: 1px solid black"></div>
    <input type="button" value="Show Computed Styles" onclick="showComputedStyles()">
</body>
</html>

IE不支持getComputedStyle()方法,currentStyle是IE浏览器的一个属性。

            var myDiv = document.getElementById("myDiv");
            var computedStyle = myDiv.currentStyle;
            alert(computedStyle.backgroundColor);   //"red"
            alert(computedStyle.width);             //"100px"
            alert(computedStyle.height);            //"200px"
            alert(computedStyle.border);            //undefined
            alert(computedStyle.borderLeftWidth);   //"1px"

getComputedStyle与style的区别

使用element.style也可以获取元素的CSS样式声明对象,但是其与getComputedStyle方法还有有一些差异的。

只读与可写
正如上面提到的getComputedStyle方法是只读的,只能获取样式,不能设置;而element.style能读能写,能屈能伸。

获取的对象范围
getComputedStyle方法获取的是最终应用在元素上的所有CSS属性对象(即使没有CSS代码,也会把默认的都显示出来);而element.style只能获取元素style属性中的CSS样式。因此对于一个光秃秃的元素<p>,getComputedStyle方法返回对象中length属性值(如果有)就是190+, 而element.style就是0。

 

posted @ 2015-07-08 16:11  bingoart  阅读(1613)  评论(0)    收藏  举报