<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <input type="text"> <script> var input=document.querySelector("input"); document.addEventListener('keyup',function(e){ //console.log(e.keyCode); if(e.keyCode===83) { input.focus(); } }) </script> </body> </html>
Effect: when the user presses a keyboard "s" key, the search box automatically obtains focus
The core idea of: detecting whether the user has pressed the "s" button, if pressed, put the cursor to the search box
Using the keyboard event object inside keyCode determines whether the user presses the "s" key
Note: Use keyboard events "keyup", if you use "keydown", a user presses the s key, not only to get the cursor, but also the "s" into the search box, as long as s key does not bounce will trigger the keyboard events, but with keyup event, a pop-up keyboard, the end of the button, you can avoid the "s" into the search box.