2017-10-13 1 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 단위로 한 번만 실행하고 싶다고 생각합니다.

이 예제를 시도하고 당신이 필요한 경우 참조 : 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

그것은했다! 정말 고맙습니다! –

관련 문제