我有 jQuery 代码,它制作了一组可聚焦元素并将 .keydown 绑定到左右箭头以通过它们制表符。在 Chrome、IE 和 Safari 中,以 return false 开头preventDefault()
或结尾(从技术上讲,我不想使用它,因为我不需要stopPropagation()
)防止箭头的默认事件,但在 Firefox 中它不会。
如何防止 Firefox 中的默认操作?
这是代码,它按预期工作,除了在我的回调之外触发默认事件的 Firefox 中。
$(function () {
var focusables = $(":focusable");
focusables.eq(0).focus();
focusables.eq(0).select();
focusables.each(function () {
$(this).keydown(function (e) {
if (e.which == '37') { // left-arrow
e.preventDefault();
var current = focusables.index(this),
next = focusables.eq(current - 1).length ? focusables.eq(current - 1) : focusables.eq(0);
next.focus();
next.select();
}
if (e.which == '39') { // right-arrow
e.preventDefault();
var current = focusables.index(this),
next = focusables.eq(current + 1).length ? focusables.eq(current + 1) : focusables.eq(0);
next.focus();
next.select();
}
});
});
});