使用原生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;
            width: 100px;
            height: 60px;
            background-color: green;
            color: #fff;
            border: none;
        }
        div {
            width: 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>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM