首页 > 其他 > 详细

getComputedStyle()方法

时间:2015-07-08 18:26:24      阅读:193      评论:0      收藏:0      [点我收藏+]

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。

 

getComputedStyle()方法

原文:http://www.cnblogs.com/bingoart/p/4630534.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!