1

我有一个像这样的 4x3 div 网格框:

        <div id="MainDiv" style="border:1px solid black; width:122px; height:160px;">
        <div id="Column1" style="float:left">
            <div id="sq1" style="width:40px; height:40px;">
            </div>
            <div id="sq2" style="width:40px; height:40px;">
            </div>
            <div id="sq3" style="width:40px; height:40px;">
            </div>
            <div id="sq4" style="width:40px; height:40px;">
            </div>
        </div>
        <div id="Column2" style="float:left">
            <div id="sq5" style="width:40px; height:40px;">
            </div>
            <div id="sq6" style="width:40px; height:40px;">
            </div>
            <div id="sq7" style="width:40px; height:40px;">
            </div>
            <div id="sq8" style="width:40px; height:40px;">
            </div>
        </div>
        <div id="Column3" style="float:left">
            <div id="sq9" style="width:40px; height:40px;">
            </div>
            <div id="sq10" style="width:40px; height:40px;">
            </div>
            <div id="sq11" style="width:40px; height:40px;">
            </div>
            <div id="sq12" style="width:40px; height:40px;">
            </div>
        </div>

如何只编写几行代码来自动化整个过程?

4

2 回答 2

0

您可以使用 java 脚本来迭代和动态创建元素。

此代码有效。||使用元素||

<script type="text/javascript">
var my_div = null;
var mainDiv = null;
var column = null;
var sq = null;
function addElement()
{
  // create a new div element
  // and give it some content
  mainDiv = document.createElement("div");
  mainDiv.setAttribute('id', 'MainDiv');  
  mainDiv.setAttribute('style', 'border:1px solid black; width:122px; height:160px;');

  var i=0,id;
  var k= 1;
  for(j=0;j<3;j++) {
      column = document.createElement("div");
      column.setAttribute('id', 'Column' + (j+1));  
      column.setAttribute('style', 'float:left');

      for(i=0; i<4; i++) {
          sq = document.createElement("div");
          sq.setAttribute('id', "sq" + k);  
          sq.setAttribute('style', 'width:40px; height:40px;');
          k++;

          column.appendChild(sq);
      }

      mainDiv.appendChild(column);
  }
  // add the newly created element and it's content into the DOM
  my_div = document.getElementById("org_div1");
  document.body.insertBefore(mainDiv, my_div);
}

</script>

<body onload="addElement()">
<div id='org_div1'> The text above has been created dynamically.</div>
</body>
</html>
于 2012-09-21T04:04:08.023 回答
0

jsfiddle在这里:

http://jsfiddle.net/UnMJq/1/

那是你要的吗?

于 2012-09-21T04:03:17.623 回答