在Firefox中阻止jQuery keydown的默认事件

6
我有一段jQuery代码,用于创建一个可聚焦元素的数组,并绑定.keydown事件以通过按左右箭头键来进行遍历。在Chrome、IE和Safari中,以preventDefault()开头或以return 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();
            }
        });
    });
});
2个回答

8

需要取消的是keypress事件,但是Firefox在这种情况下忽略preventDefault()方法。因此解决方案是将当前下拉框失焦,让keypress事件在文档上触发,并通过timeout设置焦点到新的下拉框。

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);
        }
    });
});

Demo at http://jsfiddle.net/roberkules/3vA53/


这对我不起作用。也许你的代码之所以能够工作,是因为你使用了输入文本框,而我主要是在导航下拉框。当我导航到下一个下拉框时,新聚焦列表的值会更改为下一个值。 - Brandon
我知道了,一旦 jsfiddle 恢复在线状态,我会看一下。 - roberkules
不客气。很抱歉,我看不到真正的解决方案,只有这个变通方法。 - roberkules

1

你试过这个吗?

$(selector).click(function(event) {
   event.preventDefault();
});

@Brandon 点击此链接查看 Firefox 支持情况:http://stackoverflow.com/a/31206759/1185136 - Rudey

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接