首页 > 解决方案 > 在页面加载时,在 DIV 中填充随机颜色。用随机颜色填充另外 4 个 div... 点击这 4 个 div 中的任何一个,以 9:1 的比例填充主 div

问题描述

在页面加载时,在 DIV 中填充随机颜色。用随机颜色填充另外 4 个 div... 单击这 4 个 div 中的任何一个,选择单击的 div 的颜色并以 9:1 的比例填充主 div(主 div 的 90% 和单击的 div 的 10%)...我的解决方案看起来太长了......它可以更短吗?//我的解决方案文档

        <style>
            #main {
                height: 200px;
                width: 260px;
                display: block;
                margin: 10px;
            }

            #container div {
                height: 50px;
                width: 50px;
                display: inline-block;
                margin: 10px;

            }
        </style>
    </head>
    <body>
<div id='main'></div>

<div id='container'></div>

    </body>

    <script>
        function getRandomColor() {
            const randomColor = { r: getRandomArbitrary(0, 255), g: getRandomArbitrary(0, 255), b: getRandomArbitrary(0, 255) };
            return randomColor;
        }
        function getRandomArbitrary(min, max) {
            return Math.round(Math.random() * (max - min) + min);
        }        
        const colorCode = getRandomColor();
        document.getElementById('main').style.backgroundColor = "rgb("+colorCode.r+","+colorCode.g+","+colorCode.b+")"; 

        let container = document.getElementById('container');

        for(let i=0; i<4; i++) {
            const colorBlock = document.createElement('div')
            const colorCode = getRandomColor();
            colorBlock.style.backgroundColor = "rgba("+colorCode.r+","+colorCode.g+","+colorCode.b+")";
            container.appendChild(colorBlock);
        }

        container.addEventListener('click', updateColor, false)

        function updateColor() {
            const mainDivColor = getComputedStyle(document.getElementById('main')).backgroundColor;
            const mainDivColorStr = mainDivColor.substring(mainDivColor.indexOf('(')+1, mainDivColor.indexOf(')'));
            const mainDivColorArr = mainDivColorStr.split(',').map(function(item) { return item.trim();});

            const currentColor = getComputedStyle(event.target).backgroundColor;
            const currentColorStr = currentColor.substring(currentColor.indexOf('(')+1, currentColor.indexOf(')'));
            const currentColorArr = currentColorStr.split(',').map(function(item) {return item.trim();});

            let newColor = []
            let newColorObj = {}
            let colorCodeArr = ['r','g','b']

            for(let i=0; i<mainDivColorArr.length; i++){

                newColor.push( Math.round( (mainDivColorArr[i] * 0.9) +  (currentColorArr[i] * 0.1) ));
            }

            //TODO - build object dynamically
            newColorObj={'r': newColor[0], 'g': newColor[1], 'b':newColor[2]}

            console.log(newColorObj)
            document.getElementById('main').style.backgroundColor = "rgba("+newColorObj.r+","+newColorObj.g+","+newColorObj.b+")"; 
        }

    </script>
</html>

标签: javascriptbackground-colordom-manipulation

解决方案


推荐阅读