6

我有 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();
            }
        });
    });
});
4

2 回答 2

8

keypress 事件是需要取消的事件,但 Firefox 在这种情况下会忽略 preventDefault()。所以解决方案是模糊当前的下拉菜单,让 keypress 事件在文档上触发,并通过超时将焦点设置到新的下拉菜单。

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

演示在http://jsfiddle.net/roberkules/3vA53/

于 2011-05-23T21:51:16.360 回答
1

你试过这个吗?

$(selector).click(function(event) {
   event.preventDefault();
});
于 2011-05-23T20:16:22.580 回答