使用 for 循环创建 JavaScript 中的特定 div 后,如何定位它们?

由于这是一个 Etch-a-Sketch 剽窃,我需要能够不按顺序对 div 进行着色,但是,我设置的 for 循环会遍历每个方块,并在仅接触其中一个方块后将它们全部着色。


JavaScript:


const container = document.getElementById("container");

    

    function makeRows (rows, columns) {

        container.style.setProperty('--grid-rows', rows);

        container.style.setProperty('--grid-cols', columns);

        for (c = 0; c < (rows * columns); c++) {

            let cell = document.createElement("div");

            //cell.innerText = (c + 1);

            container.appendChild(cell).className = "grid-item";

        }

    

    }

    

    //Draw Board

    makeRows(16, 16);

    

    //Paint on board

    const paint = document.querySelector("div.grid-item");

    

        paint.addEventListener('mouseover', function(){

            let paintBrush = document.getElementsByClassName('grid-item');

            

            for (let i = 0; i < paintBrush.length; i++)

            {

                paintBrush[i].style.backgroundColor = "black";

            }

            console.log("AHH HELP AHH");

    

    

        });

CSS:


:root {

    --grid-cols: 0;

    --grid-rows: 0;

  }

  

  #container {

    display: grid;

    padding: 10em;

    height: 40vh;

    width: 50vh;

    margin-left: auto;

    margin-right: auto;

    grid-template-rows: repeat(var(--grid-rows), 1fr);

    grid-template-columns: repeat(var(--grid-cols), 1fr);

    

  }

  

  .grid-item {

    padding: 1em;

    border: 1px solid #ddd;

    text-align: center;


  }


一只斗牛犬
浏览 122回答 1
1回答

慕勒3428872

我认为您可以通过类名获取所有元素(然后循环遍历它们以单独添加侦听器。请参阅下面的演示const container = document.getElementById("container");function makeRows(rows, columns) {&nbsp; container.style.setProperty('--grid-rows', rows);&nbsp; container.style.setProperty('--grid-cols', columns);&nbsp; for (c = 0; c < (rows * columns); c++) {&nbsp; &nbsp; let cell = document.createElement("div");&nbsp; &nbsp; //cell.innerText = (c + 1);&nbsp; &nbsp; container.appendChild(cell).className = "grid-item";&nbsp; }}//Draw BoardmakeRows(16, 16);//Paint on boardconst paint = document.getElementsByClassName("grid-item");for (var idx = 0; idx < paint.length; idx++) {&nbsp; paint[idx].addEventListener('mouseover', function() {&nbsp; &nbsp; this.style.backgroundColor = "black";&nbsp; });}:root {&nbsp; --grid-cols: 0;&nbsp; --grid-rows: 0;}#container {&nbsp; display: grid;&nbsp; padding: 10em;&nbsp; height: 40vh;&nbsp; width: 50vh;&nbsp; margin-left: auto;&nbsp; margin-right: auto;&nbsp; grid-template-rows: repeat(var(--grid-rows), 1fr);&nbsp; grid-template-columns: repeat(var(--grid-cols), 1fr);}.grid-item {&nbsp; padding: 1em;&nbsp; border: 1px solid #ddd;&nbsp; text-align: center;}<div id="container"></div>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript