简体   繁体   中英

How do I capture when a user presses CTRL + S?

I have a website which can save sessions but I think buttons are ugly so I thought that shortcuts would be easier, and I would prefer the onkeydown HTML tag function. The shortcut I want to use is CTRL + S . For example

<input type="text" onkeydown="if(event.keyCode == CTRL+S) saveSession()">

I'm in love with the Mousetrap library: https://craig.is/killing/mice . It normalizes keybindings with great browser support.

For example:

Mousetrap.bind('ctrl+s', function(e) {
    alert('Save!');
});

Since ctrl isn't used for saving on a Mac, you can bind multiple key combinations to the save function, eg

Mousetrap.bind(['ctrl+s', 'command+s'], function(e) {
    alert('Save!');
});

Added a solution for Windows and Mac, previously answered for Mac only.

document.addEventListener('keydown', (e) => {
  if (e.keyCode === 83 && (navigator.platform.match('Mac') ? e.metaKey : e.ctrlKey)) {
    e.preventDefault();
    alert('captured');
  }
});

Add the above code in a function and call it onkeydown . Some explanation of how the code works..

First we check the keycode for s which is 83 , and later, we check if the user also presses ctrl key if on Windows using e.ctrlKey (e is the event here) and if it's mac then check for the metaKey .

Last, am using (e) => {} is an ES6 shorthand for function(e) {} .

Demo

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