程序生成3000个正方形 [英] Generate 3000 squares procedurally

查看:158
本文介绍了程序生成3000个正方形的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要构建一个包含3000个方块的小部件。手动执行此操作需要很长时间,也许有些人知道最简单的方法来生成类.square 3000次?我还需要能够改变每个方块的内容,例如颜色,标题等.Thx朋友们!

I need to build a widget that contains 3000 squares. Doing this manually would take a very long time, maybe some of you know the easiest way to generate the class .square 3000 times? I need also be able to alter the content of each square, for example a color, title, etc. Thx friends!

<div class="square">
  <h1>10</h1>
</div>

https://jsfiddle.net/srowf8hg/

推荐答案

你只需要一个循环并创建一个新的每次迭代都是正方形。为了能够单独访问每个方块,每个生成的方块都有自己唯一的ID:

You just need a loop and create a new square on each iteration. In order to be able to access each square individually, each generated square gets its own unique id:

var cont = document.getElementById("container");

for(var i = 1; i <3001; ++i){
 var div = document.createElement("div");
 div.setAttribute("class", "square");
 div.setAttribute("id", "div" + i);
 
 var h1 = document.createElement("h1");
   h1.textContent = i;
   div.appendChild(h1);
   cont.appendChild(div);
 }

.square{
  background:#fa5339;
  color:#fff;
  width:100px;
  height:100px;
  float:left;
  border:1px solid #d63d26;
}
h1{
    height: 50%; 
    width:100%;
    display:flex;
    align-items: center;
    justify-content: center;
}

<div id=container>
  
</div>

这篇关于程序生成3000个正方形的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆