用方向鍵操作介面(例如表格上下移動、地圖平移)需要攔下鍵盤事件並判斷 keyCode。方向鍵的 keyCode 是固定的四個值:左 37、上 38、右 39、下 40,記住這組數字就能動工。
<script type="text/javascript">
function jumpPage() {
if (event.keyCode == 37) fun_a(); // 左
if (event.keyCode == 38) fun_b(); // 上
if (event.keyCode == 39) fun_c(); // 右
if (event.keyCode == 40) fun_d(); // 下
}
function fun_a() { window.alert('你按下了左'); }
function fun_b() { window.alert('你按下了上'); }
function fun_c() { window.alert('你按下了右'); }
function fun_d() { window.alert('你按下了下'); }
document.onkeydown = jumpPage;
</script>
把分派邏輯換成實際操作,就能做出鍵盤選取表格列的效果:
<table width="100%" border="1" cellspacing="1" cellpadding="0" id="table">
<tr id="lineone" style="background-color:#00cccc;">
<td id="aa" height="23"></td>
<td id="aa">按向下鍵</td>
<td id="cc">按向下鍵</td>
<td id="dd">按向下鍵</td>
<td id="ee">按向下鍵</td>
</tr>
<tr id="linetwo" style="background-color:#ffffff;">
<td id="a" height="23"></td>
<td id="b">按向上鍵</td>
<td id="c">按向上鍵</td>
<td id="d">按向上鍵</td>
<td id="e">按向上鍵</td>
</tr>
</table>
<script language="javascript">
function keyDown(e) {
var iekey = event.keyCode;
action(iekey);
}
document.onkeydown = keyDown;
function action(iekey) {
if (iekey == 40) { // 下
lineone.style.backgroundColor = "";
linetwo.style.backgroundColor = "#00cccc";
}
if (iekey == 38) { // 上
lineone.style.backgroundColor = "#00cccc";
linetwo.style.backgroundColor = "";
}
}
</script>
方向鍵會帶動頁面捲動。攔下 37 到 40 之後,記得回傳 false 或呼叫 preventDefault(),否則畫面會一邊換焦點一邊整體捲動。
別忘了跨瀏覽器取值。直接讀全域 event 是 IE 時代的寫法,標準做法是從監聽函式的參數拿:
document.onkeydown = function(e) {
e = e || window.event;
var key = e.keyCode;
// ...
e.preventDefault ? e.preventDefault() : (e.returnValue = false);
return false;
};
另外範例中多個 td 共用同一個 id(aa 出現了兩次),id 在文件中必須唯一,這裡改用 class 才是正確做法。