jQuery兼容HOVER和FOCUS(鼠标和键盘)

DA.*_*DA. 2 jquery hover keyboard-events

我正在构建一个大型菜单,我希望能够通过悬停(使用鼠标)和焦点(例如通过键盘对其进行跳转)来触发菜单.

这就是我现在正在做的事情:

$(".megaMenu-trigger").focus(function (){$(this).hover()});
$(".megaMenu-trigger").hover(function(){
    // do the stuff
});
Run Code Online (Sandbox Code Playgroud)

这是有效的,但我想知道这是否是一起处理键盘和鼠标交互的理想方式.

Aly*_*Aly 11

您可以使用bind方法将多个事件绑定到一个动作,即

$('.megaMenu-trigger').bind("mouseenter focus mouseleave", 
        function(event) { console.log(event.type); }); 
Run Code Online (Sandbox Code Playgroud)

  • 现在看起来像 jQuery 1.7+ [更喜欢](http://api.jquery.com/bind/) 你使用 `.on()` 而不是 `.bind()`。对于这个答案,语法几乎相同。只需将`bind` 替换为`on`,即:`$('.megaMenu-trigger').on("mouseenter focus mouseleave", function(event) { console.log(event.type); });` (2认同)