javascript 模拟Tab切换焦点

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Tab Key Focus Navigation</title>
</head>
<body>
<input type="text" id="input1" placeholder="Input 1" />
<input type="text" id="input2" placeholder="Input 2" />

<script>
document.addEventListener("keydown", function (event) {
console.log(event.key)
const inputs = document.querySelectorAll("input"); // 获取所有input元素
const focusedIndex = Array.from(inputs).indexOf(document.activeElement); // 获取当前焦点的index
const totalInputs = inputs.length; // input元素总数
let nextIndex = focusedIndex; // 初始化下一个焦点的index为当前焦点index

if (event.key === "Enter") {
// 检查是否按下Tab键
event.preventDefault(); // 阻止默认的Tab行为,以避免表单提交等
if (!event.shiftKey) {
// 如果不是按下Shift+Tab,则切换到下一个元素
nextIndex = (focusedIndex + 1) % totalInputs; // 计算下一个元素的index
} else {
// 如果是按下Shift+Tab,则切换到上一个元素
nextIndex = (focusedIndex + totalInputs - 1) % totalInputs; // 计算上一个元素的index
}
inputs[nextIndex].focus(); // 将焦点移动到计算出的下一个元素
}
});
</script>
</body>
</html>