获取元素的外联样式

Posted 荣洋

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了获取元素的外联样式相关的知识,希望对你有一定的参考价值。

我们都知道在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];
                }
            }

 

以上是关于获取元素的外联样式的主要内容,如果未能解决你的问题,请参考以下文章