码迷,mamicode.com
首页 > 其他好文 > 详细

获取元素的外联样式

时间:2017-03-31 20:44:17      阅读:137      评论:0      收藏:0      [点我收藏+]

标签:get   nts   color   odi   选择   div   ret   获取   ack   

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

 

获取元素的外联样式

标签:get   nts   color   odi   选择   div   ret   获取   ack   

原文地址:http://www.cnblogs.com/rongy/p/6653385.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!