2011-05-23 65 views
5

我有jQuery代碼,它使得可聚焦元素的數組和綁定.keydown左右箭頭來通過它們進行選項卡。在Chrome,IE和Safari中以preventDefault()開頭或以返回錯誤結束(技術上我不想使用因爲我不需要stopPropagation())會阻止箭頭的默認事件,但在Firefox中不會。防止在Firefox中使用jQuery keydown的默認事件

如何防止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(); 
      } 
     }); 
    }); 
}); 

回答

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

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

+0

這不適用於我。也許這是適用於你的代碼的原因是因爲你是使用輸入文本框,因爲我主要在導航下拉框,當我導航到下一個下拉框時,新聚焦的列表的值將變爲下一個值 – Brandon 2011-05-24 14:52:35

+0

我看到,一旦jsfiddle回來在線我會看看。 – roberkules 2011-05-24 15:00:58

+0

我在OP中添加了我的代碼。 – Brandon 2011-05-24 15:59:11

0

你試過嗎?

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

是,它並不適用於Firefox的工作。 :( – Brandon 2011-05-23 20:26:10

+0

@Brandon [看這裏](http://stackoverflow.com/a/31206759/1185136)支持Firefox。 – 2015-07-03 12:33:48