[英]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.