Вы забываете, что все, что вы делаете со страницей, должно быть очищено, или последствия того, что вы сделали, все равно останутся.
Когда вы установите новую функцию mouseover
, сначала необходимо удалить old mouseover
с помощью removeEventListener
. Вы также захотите удалить другие классы, которые пользователь мог добавить к элементам в прошлом, при наведении курсора мыши перед добавлением нового класса.
Попробуйте это:
const container = document.getElementById("container");
const btn = document.querySelector('button');
let y = document.querySelectorAll('button');
y.forEach(button => {
button.addEventListener('click', () => {
let choice = button.innerHTML;
switch (choice) {
case "Random Color":
random();
break;
case "Black":
blackchange();
break;
case "Eraser":
reset();
break;
}
});
});
var currentMouseoverFunction = function() {};
function blackchange() {
container.removeEventListener('mouseover', currentMouseoverFunction);
currentMouseoverFunction = function(e) {
e.target.classList.remove('random');
e.target.classList.remove('reset');
e.target.classList.add('black');
};
container.addEventListener('mouseover', currentMouseoverFunction);
};
function random() {
container.removeEventListener('mouseover', currentMouseoverFunction);
currentMouseoverFunction = function(e) {
e.target.classList.remove('black');
e.target.classList.remove('reset');
e.target.classList.add('random');
};
container.addEventListener('mouseover', currentMouseoverFunction);
};
function reset() {
container.removeEventListener('mouseover', currentMouseoverFunction);
currentMouseoverFunction = function(e) {
e.target.classList.remove('black');
e.target.classList.remove('random');
e.target.classList.add('reset');
};
container.addEventListener('mouseover', currentMouseoverFunction);
};
function makeRows(rows, cols) {
container.style.setProperty('--grid-rows', rows);
container.style.setProperty('--grid-cols', cols);
for (c = 0; c < (rows * cols); c++) {
let cell = document.createElement("div");
container.appendChild(cell).className = "griditem";
};
};
makeRows(16, 16);
#container{
width:160px;
height:160px;
margin-top:10px;
background:#eee;
}
#container div {
float:left;
height: 10px;
width: 10px;
}
.black {
background: black;
}
.random {
background: pink;
}
.reset {
background: transparent;
}
<section class="back">
<h1>
<center> Claudia Etch-A-Sketch!</center>
</h1>
</section>
<section>
<div>
<button class="Black">Black</button>
<button class="Random">Random Color</button>
<button class="Clear">Eraser</button>
</div>
</section>
<section>
<div id="container"> </div>
</section>
Я добавил свой простой CSS для целей тестирования, потому что у меня не было доступа к вашему.