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>
添加回答
举报