【问题标题】:dynamic css grid generation动态 CSS 网格生成
【发布时间】:2021-01-05 19:04:34
【问题描述】:

我想知道如何在 reactJs 或 vanila javascript 中创建这个网格?

我曾尝试使用 nth-child,但它只适用于奇数或偶数或特定的孩子。

enter image description here

【问题讨论】:

标签: javascript jquery css reactjs


【解决方案1】:

您可以这样做,这适用于 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>

【讨论】:

  • 试试我的新答案,你可以按数字选择你想要的孩子......
【解决方案2】:

这个呢?

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>

【讨论】:

  • 谢谢,但它需要是动态的,所以第 1 列(蓝色)有人可以选择 2 而不是 4。您的解决方案是对类进行硬编码
猜你喜欢
  • 2020-01-21
  • 2015-04-11
  • 2017-11-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-09-06
相关资源
最近更新 更多