当前位置: 移动技术网 > IT编程>开发语言>JavaScript > JavaScript自定义getStyle方法获取元素样式

JavaScript自定义getStyle方法获取元素样式

2020年04月11日  | 移动技术网IT编程  | 我要评论

兼容性

兼容性如下图所示摘自 mdn

解决方法

由于getcomputedstyle方法在ie浏览器中只兼容ie9及其以上,而ie8和它之前的浏览器则需要使用currentstyle方法来获取样式,所以我们就可以自定义一个getstyle方法来解决兼容性的问题

代码

自定义getstyle()代码

function getstyle (obj, name) {
    if (obj.currentstyle) {
        return obj.currentstyle[name];
    }
    else {
        return getcomputedstyle(obj)[name];
    }
}

完整html代码

<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>getstyle</title>
    <style>
        div{
            width: 200px;
            height: 200px;
            background-color: brown;
        }
    </style>
    <script>
        function getstyle (obj, name) {
            if (obj.currentstyle) {
                return obj.currentstyle[name];

            }
            else {
                return getcomputedstyle(obj)[name];
            }
        }
        window.onload = function () {
            // let box = document.queryselector("div");
            var box = document.getelementsbytagname("div")[0];
            var btn = document.getelementsbytagname("button")[0];
            box.style.width = "250px";
            box.style.height = "250px";
            box.style.backgroundcolor = "skyblue";
            btn.onclick = function () {
                alert(getstyle(box, "backgroundcolor"));
            };
        };
    </script>
</head>
<body>
    <div></div>
    <button>fun</button>
</body>
</html>

运行结果

  1. ie8

    2.ie11

    3.chrome

    4.firefox

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网