Prevent keypress to bubble to input in mousetrap

别说谁变了你拦得住时间么 提交于 2019-12-12 01:57:17

问题


I am using mousetrap for capturing key presses. One of the shortcuts I want to define is to focus on an input.

Mousetrap.bind('i', function() { $('.input').focus() });

The focussing works fine, but the 'i' keypress also gets bubbled to the input, and with being focussed, the input also gets populated with 'i'.

Is there a way to prevent the 'i' from being written in the input? Any help is appreciated.

Thanks


回答1:


Right there in the documentation:

As a convenience you can also return false in your callback:

Mousetrap.bind(['ctrl+s', 'meta+s'], function(e) {
    _saveDraft();
    return false;
});

Returning false here works the same way as jQuery's return false. It prevents the default action and stops the event from bubbling up.

So:

Mousetrap.bind('i', function() {
    $('.input').focus();
    return false;
});


来源:https://stackoverflow.com/questions/29087791/prevent-keypress-to-bubble-to-input-in-mousetrap

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!