知道一个div的宽高背景色,如何不通过写在行间样式的办法更改样式?currentStyle(只兼容ie),getComeputedStyle(兼容)-->获取非行间样式

知道一个div的宽高背景色,如何不通过写在行间样式的办法更改样式?currentStyle(只兼容ie),getComeputedStyle(兼容ie9以上)-->获取非行间样式

 (1)currentStyle 仅支持ie

<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>返回值</title>
</head>
<style type="text/css">
#div1{width: 200px;height: 200px;background: red;}
</style>
<script type="text/javascript">
window.onload=function(){
    var oDiv=document.getElementById('div1');
    alert(currentStyle.width);

}
</script>
<body>
<div id="div1"></div>
</body>
</html>

 (2)getComputedStyle,有两个参数,第二个参数可以为任何数,不起实质性作用。

<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>返回值</title>
</head>
<style type="text/css">
#div1{width: 200px;height: 200px;background: red;}
</style>
<script type="text/javascript">
window.onload=function(){
    var oDiv=document.getElementById('div1');
    alert(getComputedStyle(oDiv,false).width);

}
</script>
<body>
<div id="div1"></div>
</body>
</html>

兼容所有浏览器的写法

<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>返回值</title>
</head>
<style type="text/css">
#div1{width: 200px;height: 200px;background: red;}
</style>
<script type="text/javascript">
window.onload=function(){
    var oDiv=document.getElementById('div1');
    if(oDiv.currentStyle){
        //ie
        alert(oDiv.currentStyle.width);
    }
    else{
        //ff
        alert(getComputedStyle(oDiv,false).width)
    }

}
</script>
<body>
<div id="div1"></div>
</body>
</html>

但是,在实际应用过程中,这样的写法有些复杂,通过封装一个函数来写,将来用的时候再调用。

<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>返回值</title>
</head>
<style type="text/css">
#div1{width: 200px;height: 200px;background: red;}
</style>
<script type="text/javascript">
function getStyle(obj,name){
    if(obj.currentStyle){
        return obj.currentStyle[name];
    }
    else{
        return getComputedStyle(obj,false)[name];
    }
}
window.onload=function(){
    var oDiv=document.getElementById('div1');
    alert(getStyle(oDiv,'width'));

}
</script>
<body>
<div id="div1"></div>
</body>
</html>
衣带渐宽终不悔,为伊消得人憔悴,憔悴半天也没用,还是努力起来人富贵
原文地址:https://www.cnblogs.com/zhangjingyun/p/4561648.html