我有这个问题:每当我单击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));

最佳答案

我认为您的意思是每个div只运行一次JS。

尝试以下示例,看看是否需要它:jsfiddle

function letTheGameBegin(e, r) {
    const rand = Math.floor(Math.random() * 100);
    if(!e.target.style.backgroundColor){
        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';
        }
    }
}

关于javascript - 按钮已更改颜色,即使已分配,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/46735431/

10-12 07:37