取非行间样式

198 阅读1分钟
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
        #div1 {
            width: 200px;
            height: 200px;
            background: red;
        }
    </style>
</head>

<body>
    <div id="div1"></div>
</body>

<script>

//   取非行间样式:如果样式没有写在行间,
//   那么应该利用currentStyle(IE)或者getComputedStyle(obj,false).name。
//   获取复合样式的属性时需要注明所取的明确样式
//   如获取背景颜色,需要写backgroundColor,直接写background是没有作用的,因为它无法获取复合属性

    var oDiv = document.getElementById('div1')

     oDiv.onclick = function(){

         oDiv.currentStyel?alert('width:'+ oDiv.currentStyel.width) :alert('width:'+getComputedStyle(oDiv,false).width)
     }
</script>
</html>

在chrome下显示的结果.png

这个是在IE下显示的结果.png