作为 JS 研究的一部分,我决定创建 3 个 div 并制作它,以便当您将鼠标悬停在它们上时,背景颜色会随机改变颜色。以这种方式实现了一切:
(function getColor() {
const colors = ["red", "green", "blue", "black", "magenta", "pink"];
function getRandomIntInclusive(min, max) {
min = Math.ceil(0);
max = Math.floor(6);
let output = Math.floor(Math.random() * (max - min + 1)) + min;
return output;
}
function randomColor(someRndNumber, colorArray) {
let colorResult = colorArray[someRndNumber];
return colorResult;
}
let rndResult = getRandomIntInclusive();
let rndColor = randomColor(rndResult, colors);
const getColoredDivs = document.querySelectorAll(".coloredDiv");
getColoredDivs.forEach((elem) => {
elem.addEventListener("mouseover", () => {
elem.style.backgroundColor = rndColor;
getColor();
});
});
getColoredDivs.forEach((elem) => {
elem.addEventListener("mouseout", () => {
elem.style.backgroundColor = "white";
});
});
})();
前 10-12 次迭代一切都按我的意愿进行。当您将鼠标悬停在 div 上时,背面的颜色会随机变化(在屏幕上显示为三个带有黑色边框的正方形),但随后会开始某种无休止的激烈数字随机化(我通过在 randomizer 函数中添加 console.log 进行检查) . 浏览器冻结。杀死进程的唯一方法是通过任务管理器。我认为问题在于,每次我将光标移到 div 的表面上时,都会发生从 0 到 6 的值的随机化。但我不知道如何防止这种情况
实现过于复杂..
getRandomIntInclusive(min, max) { min = Math.ceil(0); max = Math.floor(6);
Math.ceil
四舍五入到最接近的更高整数。0
..运算的含义Math.floor
向下舍入到最接近的较小整数。重点是圆6
...