繁体   English   中英

关于如何在 javascript 中结合这两个功能的提示?

[英]Tips on how I could combine these 2 functions in javascript?

我为 odin 项目制作了一个蚀刻草图,但有人告诉我可以使用参数组合我的 createGrid() 和 updateGrid() 函数。 我怎么可能go一下呢? 更新网格 function 允许用户输入任意数字并更改网格大小。

const grid = document.querySelector(".gridContainer");
const userInput = document.getElementById("quantity");
const clear = document.querySelector(".clear");


const createGrid = () => {
    for(let i = 0; i < 256; i++) {
        const div = document.createElement("div");
        div.classList.add("square");
        grid.appendChild(div);
        
        div.addEventListener("mouseenter", function () {
            div.style.backgroundColor = randomColor();
          });
    }
};

const updateGrid = () => {
    grid.innerHTML="";
    grid.style.setProperty(
        "grid-template-columns",
        `repeat(${userInput.value}, 1fr)`
    );
    grid.style.setProperty(
        "grid-template-rows",
        `repeat(${userInput.value}, 1fr)`
    );
    for (let i = 0; i< userInput.value * userInput.value; i++){
        const div=document.createElement("div");
        div.classList.add("square");
        grid.appendChild(div);
        div.addEventListener("mouseenter", function () {
            div.style.backgroundColor = randomColor();
          });
    }
};

userInput.addEventListener("change", updateGrid);

function randomColor() {
    const randomRed = Math.floor(Math.random() * 256);
    const randomGreen = Math.floor(Math.random() * 256);
    const randomBlue = Math.floor(Math.random() * 256);
    return `rgb(${randomRed}, ${randomGreen},${randomBlue})`;
  }


clear.addEventListener("click", function() {
    grid.innerHTML = "";
    userInput.value = "";
    grid.style.setProperty("grid-template-columns", `repeat(16, 1fr)`);
    grid.style.setProperty("grid-template-rows", `repeat(16, 1fr)`);
    createGrid();
  });

  createGrid();
  
 

createGrid接受一个参数,即要制作的方块数:

const createGrid = (limit = 256) => {
    for (let i = 0; i < limit; i++) {
        const div = document.createElement("div");
        div.classList.add("square");
        grid.appendChild(div);
        div.addEventListener("mouseenter", function () {
            div.style.backgroundColor = randomColor();
        });
    }
};

const updateGrid = () => {
    grid.innerHTML = "";
    grid.style.setProperty(
        "grid-template-columns",
        `repeat(${userInput.value}, 1fr)`
    );
    grid.style.setProperty(
        "grid-template-rows",
        `repeat(${userInput.value}, 1fr)`
    );
    createGrid(Number(userInput.value));
};

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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