我想在按下 tab 时将焦点限制在单个表单上。
我的意思是关注表单 1 的选项卡索引 1、2 和 3,然后在同一表单中移回 1,然后移至 2,依此类推,永远不会移至表单 2 的输入。我也不想更改选项卡索引。
<form style="background-color:red">
<input tabindex="01"/>
<input tabindex="02"/>
<input tabindex="03"/>
</form>
<form style="background-color:blue">
<input tabindex="01"/>
<input tabindex="02"/>
<input tabindex="03"/>
</form>
这不是一个好的做法,所以不要这样做,除非有真的这样做的充分理由...
但是没有内置的 HTML 方法可以做到这一点,因此我们需要使用一些 JavaScript 以及自定义 data 属性。
我认为最简单的方法是对 parent (
<form>
)使用数据属性,这样我们就不必将其单独添加到每个输入中。我把我的命名为data-tabgroup
。
那么我们需要一些JS:
// Select the tab groups based on the data attribute we added
var tabgroups = document.querySelectorAll("[data-tabgroup]");
// Loop through each to attach the listeners we need
for (var i = 0; i < tabgroups.length; i++) {
var inputs = tabgroups[i].querySelectorAll("[tabindex]");
// Loop through all of the elements we want the tab to be changed for
for (var j = 0; j < inputs.length; j++) {
// Listen for the tab pressed on these elements
inputs[j].addEventListener("keydown", function(myIndex, inputs, e) {
if (e.key === "Tab") {
// Prevent the default tab behavior
e.preventDefault();
// Focus the next one in the group
if (inputs[myIndex + 1]) {
inputs[myIndex + 1].focus();
} else { // Or focus the first one again
inputs[0].focus();
}
}
}.bind(null, j, inputs)) // Make a copy of the variables to use in the addEventListener
}
}
<form style="background-color: red" data-tabgroup>
<input tabindex="01" />
<input tabindex="02" />
<input tabindex="03" />
</form>
<form style="background-color: blue" data-tabgroup>
<input tabindex="01" />
<input tabindex="02" />
<input tabindex="03" />
</form>
就是这样!这是演示。
一些注意事项:
tabindex
的值(它只选择 HTML 中的下一个)。考虑到这一点,您只需将元素按照 tabindexes 的顺序放入数组中,或者在将它们添加到数组后按 tabindexes 对它们进行排序。tabindex
应用于您希望其影响的子项。如果您希望它默认应用于所有输入,只需将 querySelectorAll
的 inputs
值更改为 input
。如果您想要更复杂的东西,则必须根据需要更改它。<input type="text" class="first-index"/>
<input type="text" />
<button type="button" class="last-index">save</button>
<script>
$(document).on('blur','.last-index',function() {
$('.first-index').focus();
});
</script>
我实际上找到了一个简单的解决方案。
首先,我使用 tabindex 属性设置输入来控制进度,并使用唯一 ID。然后我对第一个和最后一个输入元素执行 getElementById() ,并在最后一个输入元素上设置一个事件侦听器,然后将焦点切换到第一个输入元素。
let tk_first_input = document.getElementById("first_input");
let tk_last_input = document.getElementById("last_input");
tk_last_input.addEventListener("keydown", (e) => {
if (e.key ==="Tab") {
e.preventDefault();
tk_first_input.focus();
}
})
这对我来说非常有效,因为我有多个 DIV,每个 DIV 都有一个表单。