3 回答

TA貢獻1825條經驗 獲得超6個贊
您可以在創建網格元素的循環中設置顏色,使用c % cols: 獲取列號(注意columnColors參數和倒數第二行)
function makeRows(rows, cols, columnColors) {
container.style.setProperty("--grid-rows", rows);
container.style.setProperty("--grid-cols", cols);
for (c = 0; c < rows * cols; c++) {
let cell = document.createElement("div");
cell.innerText = c + 1;
cell.style.backgroundColor = columnColors[c % cols];
container.appendChild(cell).className = "grid-item";
}
}

TA貢獻1818條經驗 獲得超11個贊
你可以試試這個:
通過訪問其屬性設置
cell
背景顏色style
隨機顏色
'#' + Math.random().toString(16).substring(2, 6)
(substring
從 2 到刪除0.
)
const container = document.getElementById("container");
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");
cell.innerText = c + 1;
cell.style['background-color'] = '#' + Math.random().toString(16).substring(2, 6)
container.appendChild(cell).className = "grid-item";
}
}
makeRows(16, 16);
#container {
display: grid;
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;
height: 100px;
width: 100px;
}
<div id="container"></div>

TA貢獻1796條經驗 獲得超7個贊
const container = document.getElementById("container");
function makeRows(rows, cols) {
container.style.setProperty("--grid-rows", rows);
container.style.setProperty("--grid-cols", cols);
let colorArray = []
for (let index = 0; index < cols; index++) {
colorArray.push(getRandomColor());
}
for (c = 0; c < rows * cols; c++) {
let cell = document.createElement("div");
cell.innerText = c + 1;
container.appendChild(cell).className = "grid-item";
cell.style.backgroundColor = `
rgb(${colorArray[c % cols].r}, ${colorArray[c % cols].g}, ${colorArray[c % cols].b})
`;
}
}
function getRandomColor(){
let r = Math.round(Math.random() * 255);
let g = Math.round(Math.random() * 255);
let b = Math.round(Math.random() * 255);
let color = {
"r" : r,
"g" : g,
"b" : b
};
return color;
}
makeRows(16, 16);
#container {
display: grid;
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;
height: 100px;
width: 100px;
}
<div id="container"></div>
添加回答
舉報