获取元素的外联样式

我们都知道在JS中,使用ele.style.width只能获取到内联样式:

<div id="box" style="background-color: red;"></div>
        <script>
            var oDiv = document.getElementById("box")
            alert(oDiv.style.backgroundColor); //red
        </script>

但是,将样式放在<style></style>标签里,我们获取到的就是空;

这时候我们就需要用到getComputedStyle方法,它接受两个参数,第一个是目标元素,第二个是要选择的伪类,第二个参数如果不选择伪类,就填null:

var oBox = document.getElementById("box");
alert(getComputedStyle(oBox,null).width); //oBox的宽度

但是,在IE中不支持这个方法,它有自己的方法,即currentStyle:

var oBox = document.getElementById("box");
alert(oBox.currentStyle.width);  //oBox的宽度

所以,我们写一个简单的兼容函数:

            function getStyle( obj , attr ){
                if ( window.getComputedStyle ) {
                    return getComputedStyle( obj , null )[attr];
                }else{
                    return obj.currentStyle[attr];
                }
            }
原文地址:https://www.cnblogs.com/rongy/p/6653385.html