获取元素样式 currentStyle 和 getcomputedStyle

场景

 你要获取某一元素的样式,可是没有获取到,返回的值为undefined,可是有时候又能成功?

为什么?

因为,xx.stly.xxx 可以获取的样式信息,是dom元素style属性里的样式,对于通过<style>标签,或外部样式表定义的,我们就无法获取了。当然,js给予的也是dom。

 

怎么办?

dom标准里有个全局方法  getComputedStyle 。可以获取到当前对象样式规则信息,这还不算完,因为IE不支持。。。

IE有自己的 currentStyle 所以,你要兼容他们,怎么做?

 

代码

 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style>
        body,html{
            height: 100%;
        }
        body{
            background-color:red;
            background-image:url(实验.png)
        }
    </style>
</head>
<body>
<div id="div1" style=''></div>
</body>
<script type="text/javascript">
window.onload = function(){
    function t (obj,sx) {
        if(obj.currentStyle){
            return obj.currentStyle[sx];
        }else{
            return getComputedStyle(obj,false)[sx];
        }
    }
        var body =document.getElementsByTagName('body');
        body[0].style.backgroundImage ="url(实验.png)";
        alert(t(body[0],"backgroundColor"));
        }
    </script>
</html>

 

大家可以试试。

 

posted on 2015-05-25 19:14  Feng枫  阅读(174)  评论(0)    收藏  举报

导航