I applied the first answer of this question into a cell I made:
var start = document.getElementById('start');
start.focus();
start.style.backgroundColor = '#000';
start.style.color = '#FFF';
function dotheneedful(sibling) {
if (sibling != null) {
start.focus();
start.style.backgroundColor = '';
start.style.color = '';
sibling.focus();
sibling.style.backgroundColor = '#000';
sibling.style.color = '#FFF';
start = sibling;
}
}
document.onkeydown = checkKey;
function checkKey(e) {
e = e || window.event;
if (e.keyCode == '38') {
// up arrow
var idx = start.cellIndex;
var nextrow = start.parentElement.previousElementSibling;
if (nextrow != null) {
var sibling = nextrow.cells[idx];
dotheneedful(sibling);
}
} else if (e.keyCode == '40') {
// down arrow
var idx = start.cellIndex;
var nextrow = start.parentElement.nextElementSibling;
if (nextrow != null) {
var sibling = nextrow.cells[idx];
dotheneedful(sibling);
}
} else if (e.keyCode == '37') {
// left arrow
var sibling = start.previousElementSibling;
dotheneedful(sibling);
} else if (e.keyCode == '39') {
// right arrow
var sibling = start.nextElementSibling;
dotheneedful(sibling);
} else if (e.keyCode == '13') {
/// ***click button?***
}
}
td, input {font-size: 1.5rem; font-family: Arial}
table {border-collapse: collapse; background: #EEE;}
td {border: 3px solid #FFF;}
.bt {padding: 0px; display:block; width: 100%; height: 100%; background: #EEE; border: 1px solid #888; border-radius: 3px;}
<table>
<tr style="text-align:center">
<td id="start"><input type='button' class="bt" value='a' onclick="functionA()"/></td>
<td><input type='button' class="bt" value='b' onclick="functionB()"/></td>
<td><input type='button' class="bt" value='c' onclick="functionC()"/></td>
</tr>
<tr>
<td><input type='button' class="bt" value='d' onclick="functionD()"/></td>
<td><input type='button' class="bt" value='e' onclick="functionE()"/></td>
<td><input type='button' class="bt" value='f' onclick="functionF()"/></td>
</tr>
</table>
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…