2017-10-13 99 views
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)); 

回答

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'; 
     } 
    } 
} 
+0

它的工作!非常感谢! –