【问题标题】:Prevent default event for jQuery keydown in Firefox阻止 Firefox 中 jQuery keydown 的默认事件
【发布时间】:2011-08-31 10:33:00
【问题描述】:

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

【问题讨论】:

    标签: jquery firefox event-handling preventdefault


    【解决方案1】:

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

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

    【讨论】:

    • 这对我不起作用。也许这适用于您的代码的原因是因为您使用的是输入文本框,而我主要是导航下拉框。当我导航到下一个下拉框时,新关注的列表的值会更改为下一个值。
    • 我明白了,等 jsfiddle 重新上线我去看看。
    • 不客气。不幸的是,我看不到真正的解决方案,只有这个解决方法。
    【解决方案2】:

    你试过了吗?

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

    【讨论】:

    猜你喜欢
    • 2013-11-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-08
    • 2022-11-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多