I am trying to create a 16x16 grid using jquery. I have a main div, and then I'm trying to create the grid within it. I am using for loops, but when the code below runs, I get a 16x32 grid.
我正在尝试使用jquery创建一个16x16网格。我有一个主要的div,然后我正在尝试在其中创建网格。我正在使用for循环,但是当下面的代码运行时,我得到一个16x32网格。
Could anyone explain what is going on and why that is happening?
任何人都可以解释发生了什么以及为什么会发生这种情况?
<html>
<head>
<title>etch-a-sketch</title>
<link type="text/css" rel="stylesheet" href="stylesheet.css"/>
</head>
<body>
<div id=main>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script type='text/javascript' src='app.js'></script>
</body>
#main {
height: 192px;
width: 192px;
background-color: antiquewhite;
}
.squares {
height: 10px;
width: 10px;
margin: 1px;
background-color: aquamarine;
display: inline-block;
}
$(document).ready(function() {
for(var x = 0; x < 16; x++) {
for(var y=0; y<16; y++) {
$("<div class='squares'></div>").appendTo('#main');
}
}
});
2 个解决方案
#1
2
You get a 16x16 grid. When you're using "inline", spaces take place. Just change the CSS code to this:
你得到一个16x16网格。当您使用“内联”时,会出现空格。只需将CSS代码更改为:
#main {
height: 192px;
width: 192px;
background-color: antiquewhite;
}
.squares {
height: 10px;
width: 10px;
margin: 1px;
background-color: aquamarine;
display: block;
float: left;
}
Note:
display: block;
float: left;
#2
0
I think your thought process was off.. I think the best way to make a 16x16 grid (256 boxes total) would be the way I went below and use css to style them.
我认为你的思维过程已关闭..我认为制作一个16x16网格(总共256个盒子)的最好方法就是我下面的方式并用css来设置它们的样式。
The HTML
<div id="main">
</div>
The CSS
#main {
width: 100%;
}
.squares {
width:6%;
height: 50px;
border: 1px solid red;
display:inline-block;
}
The Javascript
for(var x = 0; x < 256; x++) {
$("<div class='squares'>hi</div>").appendTo('#main');
}
#1
2
You get a 16x16 grid. When you're using "inline", spaces take place. Just change the CSS code to this:
你得到一个16x16网格。当您使用“内联”时,会出现空格。只需将CSS代码更改为:
#main {
height: 192px;
width: 192px;
background-color: antiquewhite;
}
.squares {
height: 10px;
width: 10px;
margin: 1px;
background-color: aquamarine;
display: block;
float: left;
}
Note:
display: block;
float: left;
#2
0
I think your thought process was off.. I think the best way to make a 16x16 grid (256 boxes total) would be the way I went below and use css to style them.
我认为你的思维过程已关闭..我认为制作一个16x16网格(总共256个盒子)的最好方法就是我下面的方式并用css来设置它们的样式。
The HTML
<div id="main">
</div>
The CSS
#main {
width: 100%;
}
.squares {
width:6%;
height: 50px;
border: 1px solid red;
display:inline-block;
}
The Javascript
for(var x = 0; x < 256; x++) {
$("<div class='squares'>hi</div>").appendTo('#main');
}