简体   繁体   中英

How to make the button to clear up the sketch?

I'm doing a project to make an etch-a-sketch every time I hover on the grid. What I'm trying to do is to make a button to clear up all the colors made. The sketch picture.

I guess what I need to do is to remove the style elements while clicking the button. But I'm just note sure how to link the button with the style elements.

 const container = document.querySelector(".container"); // const table = document.createElement('div'); // table.classList.add('grid-square'); // table.textContent = 'hello'; // container.appendChild(table); function makeTable(rows, cols) { container.style.setProperty('--grid-rows', rows); container.style.setProperty('--grid-cols', cols); for (i = 0; i < (rows * cols); i++){ const cell = document.createElement('div'); // cell.innerText = (i + 1); container.appendChild(cell).className = "table"; }; }; makeTable(16, 16); // const container = document.querySelector('.container') const grids = document.querySelectorAll('.table') grids.forEach(element => { element.addEventListener('mouseover', (e) => { e.target.style.backgroundColor = randomColor(); console.log(e) }) }); function randomColor() { var generateColor = '#' + Math.floor(Math.random()*16777215).toString(16); return generateColor; } function resizeGrid() { sketchSize = prompt("Enter 1 to 100 to resize sketch"); return sketchSize; } // const button = document.querySelector('button') // button.addEventListener('click', (e) => { // });
 :root { --grid-rows: 1; --grid-cols: 1; }.container { display: grid; /* grid-gap: 1em; */ grid-template-rows: repeat(var(--grid-rows), 1fr); grid-template-columns: repeat(var(--grid-cols), 1fr); /* border: 1px solid black; */ width: 50%; size: 960px; }.table { padding: 1em; border: 1px solid coral; text-align: center; /* border: none; */ } header { display: flex; justify-content: center; margin: 20px; gap: 10px; }
 <,DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width. initial-scale=1.0"> <title>Etch-A-Sketch</title> <script src="index.js" defer></script> <link rel="stylesheet" href="index.css"> </head> <body> <header> <button class="clear-button">Clear</button> <button class="resize">Resize</button> </header> <div class="container"></div> </body> </html>

Cheers!!

To answer my own question, I figured how to do it.

const clear = document.querySelector('.clear-button')
clear.addEventListener('click', () => {
  grids.forEach(element => {
    element.style.backgroundColor = null;
  })
})

I was struggling earlier because I'm not sure how to put other elements (eg grids) to the new eventListener.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM