简体   繁体   中英

Trigger a jQuery keyup event only when an <input> element is not focused

I can use jQuery to bind a function to a keyup event within the context of an <input> element such that the event only fires when the <input> element is focused:

$('#my-input').keyup(function(e) {
  // only fires when the focus is on the <input> element
}

How do I bind a function to a keyup event outside the context of the input element? I want to be able to trigger a keyup event only when the <input> element is not focused:

$(':not(#my-input)').keyup(function(e) {
  // this code fires regardless of whether the input element is focused
}

Unfortunately, the function above is run regardless of whether the <input> box is focused.

$('#my-input').focus(function(){
 $('body').unbind('keyup');
}).blur(function(){
 $('body').keyup(function(e) {
  //do stuff
 });
});

Another Solution is to check if the event target is an input:

   $('body').keyup(function(e) {
      if(!$(e.target).is('input')){
         console.log('i am not input');
      }            
   });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM