JavaScript 获取dom外联样式

以前都是用jquery获取,后来写了个组件遇到这个问题,才发现这里面大有文章!

代码如下:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>获取dom外链样式</title>
    <style>
        .div{font:14px/22px arial;color:#666;border:10px solid #ddd;}
    </style>
</head>
<body>
<div id="div" class="div" style="background:#f2f2f2;"></div>
<script>
    var doc = document,
        div = doc.getElementById('div');
        
    function getCurrentStyle(node) {
        var style = null;    
        if(window.getComputedStyle) {
            style = window.getComputedStyle(node, null);
            //chrome、firefox、ie9(含)+
            console.log('globalEventContext');
        }else{
            style = node.currentStyle;
            //ie7、ie8
            console.log('currentStyel');
        }    
        return style;
    }
    console.log(getCurrentStyle(div).borderLeftWidth); //10px
    console.log(getCurrentStyle(div).backgroundColor); //rgb(242, 242, 242) 

</script>
</body>
</html>

getCurrentStyle方法会返回dom的所有样式集合,试着输出了一下这个集合(想要什么样式值可以按实际输出的键值取),发现在不同浏览器下有些细微差别,比如没给dom设置border:

ie7

谷歌:

 

所以有时候取出来的值还是要做些处理,比如要获得元素的边框宽度,就需要针对浏览器差异处理下getCurrentStyle[dom].borderTopWidth的值

 

posted on 2015-11-27 17:00  吡呦一下  阅读(1033)  评论(0编辑  收藏  举报

导航