我有四个输入值,每个输入值都有一个数字。我想要做的是,一旦设置了数字,就自动将焦点设置到下一个输入。它们都有类“输入”。
这并不是很有效:
$(".inputs").keydown(function () {
$(this).next().focus();
});
发布于 2018-05-04 18:06:16
尝尝这个
jQuery.extend(jQuery.expr[':'], {
focusable: function (el, index, selector) {
return $(el).is('a, button, :input,[tabindex]');
}
});
$(document).on('keypress', 'input,select', function (e) {
if (e.which == 13) {
e.preventDefault();
// Get all focusable elements on the page
var $canfocus = $(':focusable');
var index = $canfocus.index(document.activeElement) + 1;
if (index >= $canfocus.length) index = 0;
$canfocus.eq(index).focus();
}
});
发布于 2012-05-11 01:20:10
它只会得到下一个元素,不管它是什么。您可能需要:
$(".inputs").keyup(function () {
$(this).next(".inputs").focus();
});
此外,键向上键,而不是键向下,否则它将改变太快。
发布于 2017-10-31 19:42:00
这是我用来使enter键表现为制表符的代码,即当按Enter键时聚焦到下一个元素,或者在按shift+Enter时聚焦到上一个元素。
1)本质上:
tabables = $("*[tabindex != '-1']:visible");
var index = tabables.index(element);
tabables.eq(index + 1).focus();
2)在这里,你是一个“类”,它封装了行为,考虑到了向前和向后和有效的可聚焦元素。
我希望它能有所帮助,如果有一些代码适合您的需求,请随时适应您的需求:)
EnterAsTab = function () {
this.ENTER_KEY = 13;
};
EnterAsTab.prototype.init = function () {
this.listenOnEnterKey();
};
EnterAsTab.prototype.listenOnEnterKey = function () {
var me = this;
$('form input').on('keypress', function (event) {
if (event.which === me.ENTER_KEY) {
if (!event.shiftKey)
me.findNextFocusableElement(this);
else
me.findPreviousFocusableElement(this);
event.preventDefault();
}
}
);
};
EnterAsTab.prototype.findNextFocusableElement = function (element) {
this.findFocusableElement(element, this.increaseIndex);
};
EnterAsTab.prototype.findPreviousFocusableElement = function (element) {
this.findFocusableElement(element, this.decreaseIndex);
};
EnterAsTab.prototype.findFocusableElement = function (element, callable) {
var tabables = $("*[tabindex != '-1']:visible");
var index = tabables.index(element);
var counter = 1;
var nextElement = undefined;
try {
while (true) {
if ((nextElement = tabables.eq(index + counter)).length === 0) {
break;
}
if (this.isFocusableElement(nextElement)) {
var newIndex = callable.call(this, index, counter);
tabables.eq(newIndex).focus();
break;
} else {
counter++;
}
}
} catch (error) {
console.log(error);
}
};
EnterAsTab.prototype.increaseIndex = function (index, counter) {
return (index + counter);
};
EnterAsTab.prototype.decreaseIndex = function (index, counter) {
return index - counter;
};
EnterAsTab.prototype.isFocusableElement = function (element) {
return ['SELECT', 'TEXTAREA'].indexOf(element.prop('tagName')) > -1 ||
element.is(':text') ||
element.is(':checkbox') ||
element.is(':radio');
};
var enterAsTab = new EnterAsTab();
enterAsTab.init();
https://stackoverflow.com/questions/10539113
复制相似问题