6

フォーカス可能な要素の配列を作成し、左矢印と右矢印の .keydown をバインドしてそれらをタブで移動する jQuery コードがあります。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();
            }
        });
    });
});
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 に答える