【发布时间】:2018-06-13 14:23:23
【问题描述】:
使用 for 循环,我创建了可变数量的 div,每当我用鼠标输入它们时,它们都会改变它们的背景颜色。好消息是,每个 div 最终都有自己的颜色。现在我想添加一个函数,每当我用鼠标输入它时,它会将 div 的亮度降低 10%。问题是,到目前为止,我只成功地减少了所有 div 的背景颜色,而不是个人的背景颜色。我很抱歉措辞如此糟糕,但希望能提供任何帮助。
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
<title>Etch-a-sketch</title>
</head>
<body>
<h1>Etch-a-sketch</h1>
<button id="start">Start</button>
<div id="container"></div>
</body>
<script>
//randomColor function is taken from http://www.devcurry.com/2010/08/generate-random-colors-using-javascript.html //
function randomRgb() {
col = "rgb("
+ randomColor(255) + ","
+ randomColor(255) + ","
+ randomColor(255) + ")";
}
function randomColor(num) {
return Math.floor(Math.random() * num);
}
function resetColorOfBoxes() {
boxes = document.querySelectorAll('div');
boxes.forEach(box => box.style.backgroundColor = "white");
}
function promptEntry() {
let userInput = prompt("How many rows would you like?", "Enter a number");
if (isNaN(userInput)) {
alert("That's not a valid entry. Try again");
promptEntry();
}
else {
createGrid(userInput);
}
}
function createGrid(numberOfRows) {
resetColorOfBoxes()
/*Change number of grid-template-columns and grid-template-rows under #container in stylesheet*/
document.documentElement.style.setProperty("--columns-row", numberOfRows);
let i = 0;
let numberOfBoxes = numberOfRows**2;
/*Create boxes*/
for (i; i < numberOfBoxes ; i++) {
var div = document.createElement("div");
document.getElementById("container").appendChild(div);
div.addEventListener("mouseenter", function () {
randomRgb();
this.style.backgroundColor = col;
console.log(value);
});
}
}
let btn = document.getElementById("start")
btn.addEventListener("click", promptEntry)
</script>
</html>
这是提示(取自 theodinproject.com):
(可选):不只是将网格的颜色从黑色更改为白色(例如),而是让每个通过它的鼠标更改为完全随机的 RGB 值。然后尝试让每遍只添加另外 10% 的黑色,这样只有在 10 遍之后方格才会完全变黑。
谢谢!
【问题讨论】:
标签: javascript html css brightness