Vanilla JS를 사용하여 Etch-A-Sketch 프로젝트 작업. 16 * 16 그리드를 생성하는 for 루프가있는 프로젝트에서 문제가 발생했습니다.
//makes a 16 x 16 grid - default grid
for(let i = 0; i < 16; i++){
const div = document.createElement('div');
div.style.cssText = 'border: 1px solid black; flex: 1';
container.appendChild(div);
// div.addEventListener('mouseover', changeBackground);
for (let j = 0; j < 16; j++){
div2 = document.createElement('div');
div2.classList.add('square');
div.style.display = 'flex';
div.appendChild(div2);
div2.addEventListener('mouseover', changeBackground);
}
}
Inside the inner for loop I have set up an event listener which has a callback called changeBackground()
- which will randomly change colour when the cursor hovers over the grid - what I was hoping for was to have any square on the grid change colour when the cursor goes over it. However from the image above, only the very last square on the grid changes colour when I hover over the grid freely, whereas any other square on the grid stays white and non-responsive. So my question is: Why is the last grid square in the bottom right the only one to change color whereas every other square remains blank?
function changeBackground(){
let randomColor = colors[Math.floor(Math.random() * colors.length)];
if(randomColor === '1'){
div2.style.backgroundColor = 'red';
console.log('red');
} else if(randomColor === '2'){
div2.style.backgroundColor = 'blue';
console.log('blue');
} else if(randomColor === '3'){
div2.style.backgroundColor = 'yellow';
console.log('yellow');
} else if(randomColor === '4'){
div2.style.backgroundColor = 'orange';
console.log('orange');
} else{
div2.style.backgroundColor = 'green';
console.log('green');
}
}
All you need to do is get that element reference in your changeBackground
function
function changeBackground(e){
var div = e.target; // the current div you want to change
// do your stuff
div.style.backgroundColor = 'red';
}
요소 참조를 보여주는 간단한 예제를 모았습니다. mouseover
자동으로 함수에 전달되고 (사용 button
했지만 모든 요소에서 작동합니다) 호출했습니다 e
. 그런 다음을 사용하여 현재 요소를 꺼내야 e.target
합니다.
var btns = document.getElementsByTagName('button');
for (var i = 0; i < btns.length; i++) {
btns[i].addEventListener('mouseover', whichButton);
}
function whichButton(e) {
var btn = e.target; // <- This is your current element (in your case, div2)
console.log(btn);
var span = document.getElementById('spanMO');
span.textContent = btn.textContent;
}
<button>First</button><br/>
<button>Second</button><br/>
<button>Third</button><br/>
<p>
Mouseover: <span id="spanMO"></span>
</p>
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다