javascript - 在页面加载时,在 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>
解决方案
推荐阅读
- sql-server - 为每个 SQL Server 女巫 ClickOnce 部署 Microsoft 系统 CLR 类型时出错
- java - 如何将用户函数添加到从 JasperCompilerManager 编译的 jrxml
- django - 查询集只允许我在连接中选择一个表字段
- kotlin - kotlin 多平台到 javascript:不尊重方法的命名
- ruby-on-rails - 如果记录以前不存在,update_attribute 在 first_or_create 之后不做任何事情
- angular - Visual Studio 在构建过程中截断我的 HTML 文本
- python - UTF-8 解码 ANSI 编码文件会引发错误
- ios - Microsoft for Xamarin Forms 的 active-directory-xamarin-native-v2 示例项目在 iOS 中不起作用
- javascript - 如何在带有字符串对象的 parseJson 函数中使用变量?
- c - I2C从主到从通信问题