假设您有以下表单,用户在其中输入两个数字:
<form>
<input type="text" id="x">
<input type="text" id="y">
</form>
然后你可以使用 jQuery 来生成你的网格,如下所示:
var x = parseInt($('#x').val(), 10),
y = parseInt($('#y').val(), 10);
grid(x, y);
function grid(x, y) {
var i = -1,
j = -1,
step = 5, //assuming that each grid unit = 5
$grid = $('<div>', {'id':'grid'}),
$square = $('<div>', {'class':'square'}),
$label,
w = parseInt($square.css('width'), 10) + 2; //the width of each square + 2 pixels for the borders;
$grid.width(w * x);
while(++i < x) {
while(++j < y) {
if(j === 0) {
$label = $('<span>', {'class':'label'});
$label.css('top', j * w).css('left', i * w).html(i * step);
}
if(i === 0 && j > 0) {
$label = $('<span>', {'class':'label'});
$label.css('top', j * w).css('left', i * w).html(j * step);
}
$grid.append($square.clone(), $label);
}
j = -1;
}
$('body').append($grid);
}
CSS:
#grid { overflow: hidden; border-left: 1px solid #000; border-top: 1px solid #000; position: relative; }
div.square { width: 50px; height: 50px; float: left; border-bottom: 1px dotted #000; border-right: 1px dotted #000; }
span.label { position: absolute; background: #fff; font-weight: bold; z-index: 10; }
假设这是我们的叠加层(对话框):
<div>
<input type="text" id="x">
<input type="text" id="y">
<button id="build-grid" type="button">Build grid</button>
</div>
然后,将 onclick 事件附加到 build-grid 按钮。因此,当单击按钮时,我们读取 x 和 y 值并构建网格。
$('#build-grid').on('click', function(e){
e.preventDefault();
var x = parseInt($('#x').val(), 10), //get our values from the input fields
y = parseInt($('#y').val(), 10);
grid(x, y); // build the grid
});