Use js to get the attribute value in the style sheet

Code:

<!DOCTYPE html>
<html lang="ch">
    <head>
        <meta charset="UTF-8">
        <title>使用js获取样式表中的属性值</title>
        <style type="text/css">
            * {
     
     
                margin: 0;
                padding: 0;
            }

            #box1 {
     
     
                width: 100px;
                height: 100px;
                background-color: blueviolet;
            }
        </style>

        <script type="text/javascript">
            window.onload = function () {
     
     
                var box1 = document.getElementById("box1");
                var btn = document.getElementById("btn");
                //点击按钮弹出 要获取的属性值
                btn.onclick = function () {
     
     
                    var w = getStyle(box1, "width");
                    alert(w);
                };
            };
            //编写一个函数 用来获取样式表中的属性值
            //obj 要获取样式的元素 name 要获取的样式名
            function getStyle(obj, name) {
     
     
                //getComputedStyle 别的浏览器有这个方法 但是没有currentStyle IE8有currentStyle 没有getComputedStyle
                //Window.getComputedStyle()方法返回一个对象,该对象在应用活动样式表并解析这些值可能包含的任何基本计算后报告元素的所有CSS属性的值
                return window.getComputedStyle ? getComputedStyle(obj, null)[name] : obj.currentStyle[name];
            }
        </script>
    </head>
    <body>
        <button id="btn">点我</button>
        <br/>
        <br/>
        <div id="box1"></div>
    </body>
</html>

IE8 doesn’t support let, it’s hard to feel~~ So I changed all let to var
https://blog.csdn.net/qq_43612538/article/details/108893384
Effect:
insert the picture description here
Insert picture description here
Insert picture description here
Insert picture description here

Guess you like

Origin blog.csdn.net/qq_43612538/article/details/108893445