这里给出的所有实现都有问题。有些不能在textareas和提交按钮上正常使用,大多数不允许您使用shift向后移动,如果有的话,它们都不使用tabindexes,并且它们都不是从最后到第一个或第一个到最后。
要使[enter]键的作用类似于[tab]键,但仍可正确使用文本区域和提交按钮,请使用以下代码。另外,此代码允许您使用Shift键向后移动,并且制表符从前到后和从前到后环绕。
源代码:https : //github.com/mikbe/SaneEnterKey
CoffeeScript
mbsd_sane_enter_key = ->
input_types = "input, select, button, textarea"
$("body").on "keydown", input_types, (e) ->
enter_key = 13
tab_key = 9
if e.keyCode in [tab_key, enter_key]
self = $(this)
# some controls should just press enter when pressing enter
if e.keyCode == enter_key and (self.prop('type') in ["submit", "textarea"])
return true
form = self.parents('form:eq(0)')
# Sort by tab indexes if they exist
tab_index = parseInt(self.attr('tabindex'))
if tab_index
input_array = form.find("[tabindex]").filter(':visible').sort((a,b) ->
parseInt($(a).attr('tabindex')) - parseInt($(b).attr('tabindex'))
)
else
input_array = form.find(input_types).filter(':visible')
# reverse the direction if using shift
move_direction = if e.shiftKey then -1 else 1
new_index = input_array.index(this) + move_direction
# wrap around the controls
if new_index == input_array.length
new_index = 0
else if new_index == -1
new_index = input_array.length - 1
move_to = input_array.eq(new_index)
move_to.focus()
move_to.select()
false
$(window).on 'ready page:load', ->
mbsd_sane_enter_key()
的JavaScript
var mbsd_sane_enter_key = function() {
var input_types;
input_types = "input, select, button, textarea";
return $("body").on("keydown", input_types, function(e) {
var enter_key, form, input_array, move_direction, move_to, new_index, self, tab_index, tab_key;
enter_key = 13;
tab_key = 9;
if (e.keyCode === tab_key || e.keyCode === enter_key) {
self = $(this);
if (e.keyCode === enter_key && (self.prop('type') === "submit" || self.prop('type') === "textarea")) {
return true;
}
form = self.parents('form:eq(0)');
tab_index = parseInt(self.attr('tabindex'));
if (tab_index) {
input_array = form.find("[tabindex]").filter(':visible').sort(function(a, b) {
return parseInt($(a).attr('tabindex')) - parseInt($(b).attr('tabindex'));
});
} else {
input_array = form.find(input_types).filter(':visible');
}
move_direction = e.shiftKey ? -1 : 1;
new_index = input_array.index(this) + move_direction;
if (new_index === input_array.length) {
new_index = 0;
} else if (new_index === -1) {
new_index = input_array.length - 1;
}
move_to = input_array.eq(new_index);
move_to.focus();
move_to.select();
return false;
}
});
};
$(window).on('ready page:load', function() {
mbsd_sane_enter_key();
}
textarea
从第一行的选择器中删除。在文本区域中,您希望能够使用Enter键开始新行。