html表格单元格绑定左右上下键的js代码
时间: 2024-09-17 16:04:47 浏览: 39
键盘上下键移动选择table表格行的js代码
在HTML中,你可以使用JavaScript和键盘事件处理函数来实现表格单元格(td或th)对左右上下键的导航。下面是一个简单的示例:
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Table Cell Keyboard Navigation</title>
</head>
<body>
<table id="myTable">
<tr>
<td>Cell 1</td>
<td>Cell 2</td>
</tr>
<!-- 更多行... -->
</table>
<script>
const table = document.getElementById('myTable');
let focusCell = null; // 初始化聚焦到第一行第一列
function handleKeyDown(event) {
switch (event.key) {
case 'ArrowUp':
if (focusCell.previousElementSibling) {
focusCell = focusCell.previousElementSibling;
} else if (focusCell.parentNode && focusCell.parentNode.previousElementChild) {
focusCell = focusCell.parentNode.previousElementChild;
}
break;
case 'ArrowDown':
if (focusCell.nextElementSibling) {
focusCell = focusCell.nextElementSibling;
} else if (focusCell.parentNode && focusCell.parentNode.nextElementChild) {
focusCell = focusCell.parentNode.nextElementChild;
}
break;
case 'ArrowLeft':
if (focusCell.previousElementSibling) {
focusCell = focusCell.previousElementSibling;
} else if (focusCell.parentNode && focusCell.parentNode.previousElementChild) {
focusCell = focusCell.parentNode.previousElementChild.querySelector('td, th');
}
break;
case 'ArrowRight':
if (focusCell.nextElementSibling) {
focusCell = focusCell.nextElementSibling;
} else if (focusCell.parentNode && focusCell.parentNode.nextElementChild) {
focusCell = focusCell.parentNode.nextElementChild.querySelector('td, th');
}
break;
default:
break;
}
// 如果有焦点的单元格,改变其样式表示当前选中
if (focusCell) {
focusCell.classList.add('active');
} else {
table.querySelectorAll('td, th').forEach(cell => cell.classList.remove('active'));
}
}
// 设置初始焦点
function initFocus() {
const firstRow = table.rows[0];
if (firstRow) {
focusCell = firstRow.cells[0];
}
}
// 给表格添加事件监听
table.addEventListener('keydown', handleKeyDown);
initFocus(); // 首次加载时设置焦点
</script>
<style>
.active {
background-color: yellow;
}
</style>
</body>
</html>
```
这个例子中,当用户按下方向键时,`handleKeyDown` 函数会根据按键调整 `focusCell` 的值,并相应地更新元素的样式。注意这只是一个基础示例,实际应用中可能需要考虑更多边缘情况。
阅读全文