JS基础-获取元素的样式

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style type="text/css">
        #box1{
            width: 200px;
            min-height: 100px;
            background-color: brown;
        };
    </style>
    <script type="text/javascript">
        window.onload = function(){
            // 通过currentStyle和getComputedStyle()读取到的样式都是只读的,不能修改.
            // 如果要修改,必须通过style属性.
            var btn01 = document.getElementById('btn01');
            btn01.onclick = function(){
                var box1 = document.getElementById('box1');
                /*
                    获取元素的当前显示样式
                    语法:元素.currentStyle.样式名
                    它可以用来当前元素正在显示的样式
                    如果当前元素没有设置该样式,则获取它的默认值.

                    currentStyle只有IE游览器支持,其它游览器都不支持.
                */
                // alert(box1.currentStyle.width);

                /*
                    在其它游览器中,可以使用:
                        getComputedStyle()这个方法来获取元素的样式
                        这个方法是window的方法,可以直接使用
                    需要2个参数:
                        第一个:要获取样式的元素
                        第二个:可以传递一个伪元素,一般都传null
                    该方法会返回一个对象,对象中封装了当前元素对应的样式
                        可以通过对象.样式名读取样式
                    如果获取的样式没有设置,则会获取到真实的值,而不是默认值
                    比如:没有设置width,它不会获取到auto,而是一个长度
                */
                // var obj = getComputedStyle(box1, null);
                // alert(obj.width);

                alert(getStyle(box1, 'width'));

            };
        };
        /*
            定义一个函数,用来获取指定元素的当前样式
            参数:
                obj 要获取样式的元素
                name 要获取的样式名
        */
        function getStyle(obj, name){
            // 这里要加window,如果游览器没有找到变量会报错,如果没有找到对象的属性,则是undefined.
            if (window.getComputedStyle){
                // 正常游览器的方式,具有getComputedStyle()方法.
                return getComputedStyle(obj, null)[name];
            }else{
                // IE8的方式,没有getComputedStyle()方法
                return obj.currentStyle[name];
            }
        }
    </script>
</head>
<body>
    <button id="btn01">点我</button>
    <div id="box1">

    </div>
</body>
</html>
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值