【发布时间】:2021-01-05 19:04:34
【问题描述】:
我想知道如何在 reactJs 或 vanila javascript 中创建这个网格?
我曾尝试使用 nth-child,但它只适用于奇数或偶数或特定的孩子。
【问题讨论】:
标签: javascript jquery css reactjs
我想知道如何在 reactJs 或 vanila javascript 中创建这个网格?
我曾尝试使用 nth-child,但它只适用于奇数或偶数或特定的孩子。
【问题讨论】:
标签: javascript jquery css reactjs
您可以这样做,这适用于 3x5,但您可以随意着色, 为此,您需要一个 div 样式作为网格,以便按该顺序获取它们。
const createTable = (blue,yellow,red)=>{
let x = 3;
let y = 5;
const grid = document.getElementsByClassName('mygrid')[0]
for(let i = 0;i<x;i++){
var div = document.createElement('div')
div.classList.add('createdDiv')
grid.appendChild(div)
for(let z=1;z<y;z++){
var div = document.createElement('div')
div.classList.add('createdDiv')
grid.appendChild(div)
}
}
let allDivs = document.getElementsByClassName('createdDiv');
[...allDivs].forEach((el,i)=>{
if((i+1)%x==1&&(i+1)/x >= y-blue){
el.classList.toggle('blue')
}else if( (i+1)%x==2 && ((i+1)/x) >= y-yellow ){
el.classList.toggle('yellow')
}else if((i+1)%x==0 && ((i+1)/x)> Math.abs(red-y)){
el.classList.toggle('red')
}
})
}
createTable(4,1,3)
.mygrid{
display:grid;
grid-template-columns: 33.3% 33.3% 33.3%;
}
.mygrid > div{
border:1px solid #666;
padding:20px;
text-align:center;
}
.blue{
background-color:#33f;
}
.yellow{
background-color:yellow;
}
.red{
background-color:red;
}
<div class="mygrid">
</div>
【讨论】:
这个呢?
document.querySelector(".mygrid > div:nth-child(2)").style.backgroundColor = "red";
document.querySelector(".mygrid > div:nth-child(4)").style.backgroundColor = "blue";
.mygrid{
display:grid;
grid-template-columns: 33.3% 33.3% 33.3%;
}
.mygrid > div{
border:1px solid #666;
padding:20px;
text-align:center;
}
.blue{
background-color:#33f;
}
.yellow{
background-color:yellow;
}
.red{
background-color:red;
}
<div class="mygrid">
<div style="grid-column:1/-1;">1</div>
<div >2</div>
<div class="">3</div>
<div class="">4</div>
<div class="">5</div>
<div class="">6</div>
<div class="">7</div>
<div class="e">8</div>
<div class="">9</div>
<div class="">10</div>
<div class="">11</div>
<div class="">12</div>
<div class="">13</div>
</div>
【讨论】: