按钮会改变颜色,即使已经分配了颜色

时间:2017-10-13 17:48:21

标签: javascript loops click addeventlistener minesweeper

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

1 个答案:

答案 0 :(得分:1)

我认为你的意思是你只想在每个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';
        }
    }
}