简体   繁体   中英

How to detect the “key up” event of the CTRL key when releasing CTRL-F?

I am trying to detect the "key up" event of the CTRL key when releasing CTRL+F in the browser. I have tried this:

    $(document).keyup(function(e){
        if (e.ctrlKey){ // note that I'm not even checking for the F key here
            console.log("CTRL up");
        }
    });

but it doesn't work, the event is not triggered. How can I do this?

If you're using jQuery, you can always do:

$(document).keydown(function(e) {
  if(e.ctrlKey && (e.keyCode === 70 || e.keyCode === 102)) // f or F
    alert("Ctrl+F was pressed!!");
});

from your code:

  • never use keyup , by that time the browser already fired its own event and the event will never be bubble down to the document again, at least you should use keydown
  • you will never be able to override the browser behavior, in this case, bring the search input box

e.ctrlKey returns false on keyUp event and true on keyDown. You can test (e.keyCode === 17) condition.

You were very close. I always find it easiest to output the e variable in order to see exactly what's going on and filter down from there. See my jsfiddle for a working example.

$(document).keyup(function (e) {
  if(e.originalEvent.key == 'Control') {
    console.log("CTRL keyup event.");
  }
});

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