我正在使用 jQuery 生成一个 div 网格,然后我将其样式设置为游戏的棋盘。当我将网格设置为 10 x 10 时,它工作正常,但是当我增加方 block 数量时,即使增加一个,左侧第二列要么根本不显示(尽管 html 很好),要么它扩展从网格底部向下而不是向上。
我尝试过修改样式表和代码中的几乎每个变量,但都无济于事。任何帮助将不胜感激。
$(document).ready(function() {
var row_count = 11;
var base = document.getElementById('base');
var square = '<div class="square"></div>';
var col_count = 11; // Sets the number of columns
while (col_count >= 0) { //Outer loops controls the columns.
row_count = 11; // sets the number of rows
while (row_count >= 0) {
$('<div class="square" id = "in_col' + '_' + col_count + '_' + row_count + '"></div>', {
"class": "square"
}).appendTo('#base');
row_count--;
}
col_count--;
}
// These two values, for posx and posy are the positioning
// coordinates for the squares of the grid
var posx = 10;
var posy = 10;
var col = 0; // Initiates the column counter for the below while loop
while (col <= 11) { // must match var col_count above
$.each($('div[id^="in_col_' + col + '"]'), function() {
$(this).css('top', posy);
$(this).css('left', posx);
posy += 41;
});
posy = 10;
posx += 41;
col++;
}
});
.square {
border: 1px solid black;
height: 40px;
width: 40px;
position: absolute;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='base'>
</div>
Fiddle示例
最佳答案
我对代码进行了一些重构,改用 for 循环,这样我们就不必跟踪迭代变量。我还在图 block 上使用了 float: left;
,并在我们想要换行到新行时使用了 clear: Both;
。
Javascript
$(document).ready(function() {
var col_count = 11; //Sets the number of columns
var row_count = 11; //sets the number of rows
var base = $('#base');
var square = '<div class="square"></div>';
for(var i = 0; i < col_count; i++){
for(var j = 0; j < row_count; j++){
var tile = $(square);
if(j === 0) tile.addClass('newRow');
base.append(tile);
}
}
});
CSS
.square {
border: 1px solid black;
height: 40px;
width: 40px;
float: left;
margin-top: -1px;
margin-left: -1px;
}
.newRow {
clear: both;
}
fiddle :https://jsfiddle.net/e0g6y9th/
关于javascript - 使用 jQuery 生成 DIV 网格,但如果它不是 10 x 10,则会出现奇怪的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34797839/