javascript - Encapsulate functions to achieve browser compatibility.
漂亮男人
漂亮男人 2017-06-26 10:56:44
0
1
681
<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>封装获取css属性</title>
    <style>
        h1{
            width:300px;
            height:100px;
            background-color:red;
        }
    </style>
</head>
<body>
    <h1>我是高100px,宽300px的红色长方形</h1>

    <script type="text/javascript">
        var h1 = document.getElementsByTagName('h1')[0];
        //标准浏览器
        console.log( window.getComputedStyle(h1)['width']);
        console.log( window.getComputedStyle(h1).height);
        //IE浏览器
        console.log(h1.currentStyle.width);
        console.log(h1.currentStyle.height);
        //封装函数
        //ele表示元素,zxc表示属性
        functiong abc (ele,zxc){
            //第一种
            var qwe = window.getComputedStyle( ele ).zxc||ele.current.zxc
            console.log(qwe);
            //第二种
            if (window.getComputedStyle( ele )){
                window.getComputedStyle( ele ).zxc
            }else{
                ele.current.zxc
            }
        }

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

Is this the right way to encapsulate it?

漂亮男人
漂亮男人

reply all(1)
刘奇

You need to first determine whether the function exists

function getStyle(elem, attr) {
    let style;

    if (window.getComputedStyle) { // 标准
        // 防止 elem === document
        let view = (elem.ownerDocument || elem).defaultView;

        if (!view || !view.opener) {
            view = window;
        }

        style = window.getComputedStyle(elem)[attr];
    } else if (document.documentElement.currentStyle) { // IE
        style = elem.currentStyle[attr];
    }
    elem = null;

    return style;
}
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!