使用原生JS 修改 DIV 属性

本例参考并改进自:https://www.jianshu.com/p/2961d9c317a3

大家可以一起学习!!

<!DOCTYPE html>
<html lang="CH-ZN">
<head>
    <meta charset="utf-8">
    <title>按键修改DIV属性</title>
    <style type="text/css">
        * {
            margin: 0;
            padding: 0;
        }
        body {
            text-align: center;
        }
        button {
            margin-top: 20px;
             100px;
            height: 60px;
            background-color: green;
            color: #fff;
            border: none;
        }
        div {
             400px;
            height: 400px;
            background-color: black;
            margin: 20px auto;
            display: block;
            transition: all 1s;
        }

    </style>
</head>
<body>
    <button>变宽</button>
    <button>变高</button>
    <button>变色</button>
    <button>变圆</button>
    <button>隐藏</button>
    <button>重置</button>
    <div></div>
    <script type="text/javascript">
        /**
         * 修改属性
         * @param1  元素
         * @param2  属性(注意这里是字符串类型)
         * @param3  属性值
        */
        let changeStyle = (ele, attr, value) => {
            // 注意:这里的 attr 为字符串,如果用.attr 的方式则无用
            ele.style[attr] = value;
        }


        /**
         * 随机生成 rgb 颜色
         * @param1  最小值
         * @param2  最大值
        */
        let changeColor = (min, max) => {
            r = Math.floor(Math.random() * (max - min) + min);
            g = Math.floor(Math.random() * (max - min) + min);
            b = Math.floor(Math.random() * (max - min) + min);
            return 'rgb('+ r + ',' + g + ',' + b + ')';
        } 

        window.onload = function () {
            const buttons = document.querySelectorAll('button');
            const divBox = document.querySelector('div');
            let changeAttrs = new Array('width', 'height', 'background', 'borderRadius', 'display', 'display');
            
            for (let i = 0; i < buttons.length; i++) {
                buttons[i].addEventListener('click', function () {
                    // 当按下重置按钮后将重置样式
                    i == buttons.length - 1 && (divBox.style.cssText = '');
                    // 只有当且每次按下变色的时候随机生成颜色
                    let bgColor = i == 2 ? changeColor(0, 255) : '';
                    let changValues = new Array('600px', '600px', bgColor, '50%', 'none', 'block');
                    changeStyle(divBox, changeAttrs[i], changValues[i]);
                });
            }
        }
    </script>
</body>
</html>
原文地址:https://www.cnblogs.com/duxiu-fang/p/11122871.html