<!DOCTYPE html>
<html>
<head>
<title>table支持鍵盤上下左右控制</title>
<script src="https://cdn.staticfile.org/jquery/2.0.0/jquery.min.js">
</script>
<script type="text/javascript">
$(document).ready(function(){
$(document).keydown(function(event){
// 判斷當前操作是否在table內
if("td"===document.activeElement.tagName.toLowerCase()){
var flag;
switch(event.keyCode){
case 37:// 左
flag = "left";
break;
case 38:// 上
flag = "up";
break;
case 39:// 右
flag = "right";
break;
case 40:// 下
flag = "down";
break;
}
if (flag) {
operate(flag)
}
}
// 操作單元格
function operate(flag){
// 定位當前行
var currentRow = ( $(document.activeElement).parent().parent().find("tr").index($(document.activeElement).parent()[0]));
// 定位當前列
var currentColumn = ($(document.activeElement).index());
// 獲取表格 document.activeElement:當前焦點元素
var table = document.activeElement.parentNode.parentNode.parentNode
// 總行數
var rows = table.rows.length
// 總列數
var columns = table.rows.item(0).cells.length
switch(flag){
case "up":// 上,越界判斷
if (currentRow > 0) { table.rows.item(currentRow - 1).cells.item(currentColumn).focus() }
break;
case "down":// 下,越界判斷
if (currentRow < rows - 1) { table.rows.item(currentRow + 1).cells.item(currentColumn).focus() }
break;
case "left":// 左,越界判斷
if (currentColumn > 0) { table.rows.item(currentRow).cells.item(currentColumn - 1).focus() }
break;
case "right":// 右,越界判斷
if (currentColumn < columns - 1) { table.rows.item(currentRow).cells.item(currentColumn + 1).focus() }
break;
}
}
});
});
</script>
</head>
<body >
<table border="1px" id="id">
<tr>
<td contenteditable="true">第一行第一列</td>
<td contenteditable="true">第一行第二列</td>
<td contenteditable="true">第一行第三列</td>
</tr>
<tr>
<td contenteditable="true">第二行第一列</td>
<td contenteditable="true">第二行第二列</td>
<td contenteditable="true">第二行第三列</td>
</tr>
<tr>
<td contenteditable="true">第三行第一列</td>
<td contenteditable="true">第三行第二列</td>
<td contenteditable="true">第三行第三列</td>
</tr>
<tr>
<td contenteditable="true">第四行第一列</td>
<td contenteditable="true">第四行第二列</td>
<td contenteditable="true">第四行第三列</td>
</tr>
</table>
</body>
</html>
支持鍵盤上下左右控制
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.