Javascript кнопка «клик» работает только один раз, чем нужно обновить страницу sh - PullRequest
2 голосов
/ 19 января 2020

так что я работаю над этой интерактивной сеткой и настроил ее так, чтобы при нажатии кнопки элементы сетки меняли цвет фона в соответствии с выбранной кнопкой. Моя проблема в том, что я могу нажимать каждую кнопку только один раз, и после этого она не будет работать, пока я не обновлю sh страницу. как это исправить, чтобы можно было менять цвета столько раз, сколько я хочу?

HTML

<!DOCTYPE html>
<html>
    <head> 
         <title> Claudias Etch-A-Sketch</title>
         <link rel= "stylesheet"  href="style.css">     
    </head>


<body>
   <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">Clear Board</button>
        </div>
    </section>
<section>

 <div id = "container"> </div>

</section>
</body>

<script src ="javascript.js"> </script>
</html>

JAVASCRIPT

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 "Clear Board":
                reset();
                break;
        }
    });
})


function blackchange() { const bb = container.addEventListener('mouseover', e=> e.target.classList.add('black'))};


function random() {
  const rr= container.addEventListener('mouseover', e=> e.target.classList.add('random'))
};

function reset () { const rr= container.addEventListener('mouseover', e => e.target.classList.add('reset'))};

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);

Ответы [ 2 ]

0 голосов
/ 19 января 2020

Вы забываете, что все, что вы делаете со страницей, должно быть очищено, или последствия того, что вы сделали, все равно останутся.

Когда вы установите новую функцию 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 для целей тестирования, потому что у меня не было доступа к вашему.

0 голосов
/ 19 января 2020

Ваша основная проблема заключается в том, что вы продолжаете добавлять mouseover прослушиватели событий в контейнер, и ваши ячейки в итоге имеют классы random и black. Тогда попытка добавить одно или другое ничего не изменит. Вам нужно удалить класс другого цвета и применить только тот, который вам нужен.

Вы также можете упростить свою жизнь, добавив прослушиватель событий mouseover только один раз, и использовать переменную для цвета, которая Обработчик событий будет использовать.

Попробуйте демо ниже:

const container = document.getElementById("container");
const buttons = document.querySelectorAll('button');
let cells = [];
let selectedColor = null;

buttons.forEach(button => {
    button.addEventListener('click', () => {
        switch (button.id) {
            case "black-btn":
                selectColor('black');
                break;
            case "random-btn":
                selectColor('random');
                break;
            case "clear-btn":
                reset();
                break;
        }
    });
})

container.addEventListener('mouseover', e => {
  if (selectedColor !== null) {
    e.target.classList.remove('black', 'random');
    e.target.classList.add(selectedColor);
  }
});

function reset() {
  cells.forEach(cell => cell.classList.remove('black', 'random'));
}

function selectColor(color) {
  selectedColor = color;
  buttons.forEach(button => {
    button.classList[button.id === `${color}-btn` ? 'add' : 'remove']('active');
  });
}

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");
    cells.push(cell);
    container.appendChild(cell).className = "griditem";
  };
};

makeRows(16, 16);
body { font-family: Arial, Helvetica, sans-serif; }
h1 { font-size: 16px; }
button.active { box-shadow: 0 0 3px #882ac6; }

#container {
  background: #eee;
  display: grid;
  height: 150px;
  width: 150px;
  grid-template-columns: repeat(16, 1fr);
}

.griditem.black { background: black; }
.griditem.random {
  -webkit-animation: random 3s infinite;
  animation: random 3s infinite;
}
@keyframes  random {
  0% { background-color: purple; }
  15% { background-color: red; }
  30% { background-color: yellow; }
  45% { background-color: green; }
  60% { background-color: blue; }
  75% { background-color: orange; }
  100% { background-color: purple; }
}
<h1>Claudia Etch-A-Sketch!</h1>

<div>
  <button id="black-btn">Black</button>
  <button id="random-btn">Random Color</button>
  <button id="clear-btn">Clear Board</button>
</div>

<div id="container"></div>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...