pra*_*pal 34 javascript dom-events
我有一张包含大量条目的表格.一旦我在当前文本框中输入值,我想将焦点更改为下一个文本框.并希望将此过程继续到最后一个字段.我的问题是,一旦我在文本框中输入值,是否可以通过javascript编码模拟tab键.
没有按下键盘上的Tab键,我想通过javascript带来相同的功能.这可能吗 ?
krc*_*cko 43
你只需要将焦点放在下一个输入字段上(通过在该输入元素上调用focus()方法),例如,如果你使用jQuery,这个代码将在按下enter时模拟tab键:
var inputs = $(':input').keypress(function(e){
if (e.which == 13) {
e.preventDefault();
var nextInput = inputs.get(inputs.index(this) + 1);
if (nextInput) {
nextInput.focus();
}
}
});
Run Code Online (Sandbox Code Playgroud)
Joe*_*rra 18
不久前需要模拟选项卡功能,现在我已经将它作为使用jquery 的库发布了.
EmulateTab:一个jQuery插件,用于模拟页面元素之间的标签.
您可以在演示中看到它的工作原理.
if (myTextHasBeenFilledWithText) {
// Tab to the next input after #my-text-input
$("#my-text-input").emulateTab();
}
Run Code Online (Sandbox Code Playgroud)
Gau*_*sie 13
function nextField(current){
for (i = 0; i < current.form.elements.length; i++){
if (current.form.elements[i].tabIndex == current.tabIndex+1){
current.form.elements[i].focus();
if (current.form.elements[i].type == "text"){
current.form.elements[i].select();
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
当提供当前字段时,它将使用下一个选项卡索引将焦点跳转到该字段.用法如下
<input type="text" onEvent="nextField(this);" />
Run Code Online (Sandbox Code Playgroud)
我找不到可以做我想要的答案.我有一个问题,其中有一些我不希望用户标签的链接元素.这就是我想出的:
(请注意,在我自己的代码我用a:not(.dropdown-item)的,而不是a上allElements线,为了防止用户tab键a.dropdown-item.)
function(event){
//Note that this doesn't honour tab-indexes
event.preventDefault();
//Isolate the node that we're after
const currentNode = event.target;
//find all tab-able elements
const allElements = document.querySelectorAll('input, button, a, area, object, select, textarea, [contenteditable]');
//Find the current tab index.
const currentIndex = [...allElements].findIndex(el => currentNode.isEqualNode(el))
//focus the following element
const targetIndex = (currentIndex + 1) % allElements.length;
allElements[targetIndex].focus();
}
Run Code Online (Sandbox Code Playgroud)
这将模拟表单中的选项卡,并在按下Enter键时将焦点放在下一个输入上。
window.onkeypress = function(e) {
if (e.which == 13) {
e.preventDefault();
var inputs = document.getElementsByClassName('input');
for (var i = 0; i < inputs.length; i++) {
if (document.activeElement.id == inputs[i].id && i+1 < inputs.length ) {
inputs[i+1].focus();
break;
}
}
Run Code Online (Sandbox Code Playgroud)