当前位置:   article > 正文

实现浏览器兼容版的window.getComputedStyle_getcomputedstyle的兼容写法

getcomputedstyle的兼容写法

    为实现浏览器兼容版的获取元素的实际样式,可以封装一个函数,下面是网易微专业上的一道练习题,后面是我写的代码封装函数。
getStyle函数用于获取元素的实际样式,语法如下:
    var cssPropertyValue = getStyle (element, cssPropertyName);
    使用示例如下:
     getStyle(element, “color”) 返回element元素的显示颜色,如:”rgb(0, 0, 0)”
    getStyle(element, “line-height”) 返回element元素的实际行高,如:”30px”
    请实现getStyle函数,要求浏览器兼容。

<!DOCTYPE html>
<html>
<head>
    <title>getComputedStyle - 获取样式</title>
    <style>
        div{margin: 20px auto;}
        button{padding: 4px 5px;margin-left: 10px;}
        input{width: 215px;padding: 4px 5px;border: 1px solid #ababab;border-radius: 3px;box-shadow: 2px 2px 3px #ededed inset;font-size: 14px;font-weight: bold;}

    </style>
</head>
<body>
    <div>
        <input id="mobile0" value="13564782365">
        <button id="get0">获取颜色</button>
    </div>
    <div>
        <input id="mobile1" value="13564782365" style="color: red;">
        <button id="get1">获取颜色</button>
    </div>
    <script>
    function $(id) {
        return typeof id === "string" ? document.getElementById(id) : id;
    }
    var Util = (function(document, util) {
        util = util || {};

        util.addEventListener = function(element, type, listener) {
            if (element.addEventListener) {
                element.addEventListener(type, listener, false);
            } else {
                element.attachEvent('on' + type, listener);
            }
        }
        return util;
    })(document, Util);
        //实现getStyle函数
        function getStyle(element,cssPropertyName){
            if(window.getComputedStyle){//如果支持getComputedStyle属性(IE9及以上,ie9以下不兼容)
                return window.getComputedStyle(element)[cssPropertyName];
            }else{//如果支持currentStyle(IE9以下使用),返回
                return element.currentStyle[cssPropertyName]; 
            }
        }
        Util.addEventListener($('get0'),'click',function(){
            alert(getStyle($('mobile0'),'color'));
            alert(getStyle($('mobile0'),'width'));
        });
    </script>
</body>
</html>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小小林熬夜学编程/article/detail/254427
推荐阅读
相关标签
  

闽ICP备14008679号