0
我有这个问题:每当我点击div时,我想添加背景颜色。永远。但即使我点击更多(如循环),背景更改。如何永久设置背景颜色?按钮即使已分配颜色也会更改颜色
const blocks = document.querySelectorAll('.game div');
const liveNumber = document.querySelector('.lives-num');
let lives = 1;
function letTheGameBegin(e, r) {
const rand = Math.floor(Math.random() * 100);
if (rand < 40) {
e.target.style.backgroundColor = 'green';
} else if (rand < 60) {
e.target.style.backgroundColor = 'yellow';
lives++;
} else if (rand < 90) {
e.target.style.backgroundColor = 'red';
lives--;
} else {
e.target.style.backgroundColor = 'white';
}
liveNumber.innerHTML = lives;
if (lives === 0) {
//document.querySelector('.game-over').style.display = 'flex';
}
}
blocks.forEach(block => block.addEventListener('click', letTheGameBegin));
它的工作!非常感谢! –