用jQuery写一些非常快速的解决方案。我粘贴了整个html,所以你可以将它保存为html文件并在浏览器中打开。您可以单击单元格以查看坐标(从0开始)。
<html>
<head>
<title>GRID</title>
<style type="text/css">
table tr td { width: 50px; height: 50px; background-color: silver; border: 1px solid black; }
table tr td.over { background-color: yellow; }
table tr td.active { background-color: red; }
.controls { padding: 20px; }
</style>
</head>
<body>
<div class="controls">
<a href="javascript:void(0)" data-move="[-1, 0]">left</a>
<a href="javascript:void(0)" data-move="[0, -1]">top</a>
<a href="javascript:void(0)" data-move="[1, 0]">right</a>
<a href="javascript:void(0)" data-move="[0, 1]">bottom</a>
<a href="javascript:void(0)" data-move="[-1, -1]">topleft</a>
<a href="javascript:void(0)" data-move="[1, -1]">topright</a>
<a href="javascript:void(0)" data-move="[1, 1]">bottomright</a>
<a href="javascript:void(0)" data-move="[-1, 1]">bottomleft</a>
</div>
<table></table>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var rows = 6,
cols = 7;
for(var i = 0; i < rows; i++) {
$('table').append('<tr></tr>');
for(var j = 0; j < cols; j++) {
$('table').find('tr').eq(i).append('<td></td>');
$('table').find('tr').eq(i).find('td').eq(j).attr('data-row', i).attr('data-col', j);
}
}
$('table tr td').mouseover(function() {
$(this).addClass('over');
}).mouseout(function() {
$(this).removeClass('over');
}).click(function() {
$(this).addClass('active');
});
$(".controls a").click(function() {
var $active = $("table tr td.active");
if($active.length > 0) {
var move = $.parseJSON($(this).attr('data-move'));
if(move.length >= 2) {
$active.each(function() {
var row = parseInt($(this).attr('data-row')) + move[1],
col = parseInt($(this).attr('data-col')) + move[0];
if(col >= cols) col = cols - 1;
if(col < 0) col = 0;
if(row >= rows) row = rows - 1;
if(row < 0) row = 0;
$(this).removeClass('active');
$('table tr').eq(row).find('td').eq(col).addClass('active');
});
}
}
});
});
</script>
</body>
</html>
请注意,如果你改变rows
和cols
变量可以得出更大的网格。
我已将controls
div与按钮相加,所以您可以玩指令。首先,您需要将元素标记为活动状态,并且您可以点击移动它们。
有一个错误(或我的观点),您可以标记多个字段并将它们一次全部移动。
这是开始的好基础!
你可以使用jQuery吗?会更容易... – Karol 2013-05-14 07:46:09
我不知道,idnt知道如何让jquery进入我的代码而不是如何使用它,我想我应该看看它呢? – 2013-05-15 01:20:58