我有jQuery代码,它生成一个可聚焦元素数组,并绑定.keydown左右箭头以通过它们进行选项卡。在Chrome,IE和Safari中以preventDefault()
开头或以返回false结尾(技术上我不想使用因为我不需要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();
}
});
});
});
答案 0 :(得分:7)
按键事件是需要取消的事件,但Firefox在此方案中忽略了preventDefault()。因此,解决方案是模糊当前下拉列表,让按键事件触发文档,并通过超时将焦点设置为新的下拉列表。
var focusables = $(":focusable");
focusables.eq(0).focus().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);
this.blur();
setTimeout(function() { next.focus().select(); }, 50);
}
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);
this.blur();
setTimeout(function() { next.focus().select(); }, 50);
}
});
});
演示
答案 1 :(得分:0)
你试过这个吗?
$(selector).click(function(event) {
event.preventDefault();
});