2011-05-23 146 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