• JavaScript获取HTML元素样式的方法(style、currentStyle、getComputedStyle)


    一、style、currentStyle、getComputedStyle的区别

    • style只能获取元素的内联样式,内部样式和外部样式使用style是获取不到的。

    • currentStyle可以弥补style的不足,但是只适用于IE

    • getComputedStyle同currentStyle作用相同,但是适用于FF、opera、safari、chrome

    "DOM2级样式" 增强了document.defaultView,提供了getComputedStyle()方法。

     这个方法接受两个参数:要取得计算样式的元素和一个伪元素字符串(例如“:after”)。如果不需要伪元素信息,第二个参数可以是null。

     getComputerStyle()方法返回一个CSSStyleDeclaration(CSS样式声明,如:font-size:12px)对象,其中包含当前元素的所有计算的样式。

     以下面的HTML页面为例:

    <!DOCTYPE html> 
    <html> 
    <head> 
        <title>计算元素样式</title>
        <meta charset="utf-8"> 
        <style> 
            #myDiv { background-color:blue; width:300px; height:200px; } 
        </style> 
        <body> 
            <div id ="myDiv" style="background-color:red; border:1px solid black"></div> 
            <script>     
                var myDiv = document.getElementById("myDiv");     
                var computedStyle = document.defaultView.getComputedStyle(myDiv, null);     
                console.log(computedStyle.backgroundColor);       //"red" 或 rgb(255, 0, 0)    
                console.log(computedStyle.width);                 //"100px"     
                console.log(computedStyle.height);                //"200px"   
                console.log(computedStyle.border);                //"1px solid rgb(0, 0, 0)" 或 空字符串
            </script>
    </body> 
    </head> 
    </html>

    边框属性可能也不会返回样式表中实际的border规则(Opera会返回,但其它浏览器不会)。

    存在这个差别的原因是不同浏览器解释综合属性的方式不同,因为设置这种属性实际上会涉及很多其他的属性。

    在设置border时,实际上是设置了四个边的边框宽度、颜色、样式属性。

    因此,即使 computedStyle.border不会在所有浏览器中都返回值,但computedStyle.borderLeftWidth则会返回值。

    二、封装getStyle (获取样式currentStyle getComputedStyle兼容处理)

    2.1基础版:

    <script type="text/javascript">
        function getStyle(obj, attr){
             if(obj.currentStyle){
                return obj.currentStyle[attr];
             }
             else{
                return getComputedStyle(obj, null)[attr];
             }
        }
        window.onload = function (){
            var oDiv = document.getElementById('div1');
            alert(getStyle(oDiv, 'backgroundColor'));
        }
    </script>
    <div id="div1"></div>

    2.2简洁版:

    function getStyle(obj, attr) {
        return obj.currentStyle ? obj.currentStyle[attr] : getComputedStyle(obj, false)[attr];
    }

    文章参考:http://www.candoudou.com/archives/526

         http://www.cnblogs.com/leejersey/archive/2012/08/16/2642604.html

  • 相关阅读:
    SHELL
    Docker
    RHCE内容记要
    mysql基本知识的总结
    Linux启动提示Kernel panic
    配置tomcat、nginx实现反向代理(需操作)
    linux下nginx的安装和配置
    linux下安装mysql5.7(centos6.0)
    linux打包解压包(.tar .gz .tar.gz .zip)
    多重继承下的类型转换
  • 原文地址:https://www.cnblogs.com/lvmylife/p/5387558.html
Copyright © 2020-2023  润新知