JavaScript key positioning input box

Claim:

There is an input box, when the user presses the skey, the cursor is automatically positioned in the input box.

Realization ideas:

  1. Check whether the user has pressed the skey, if the key is pressed s, the cursor is positioned in the search box
  2. Use the keyboard event object to keyCodedetermine whether the user pressed the s key
  3. The search box gets focus: how to use focus()it

Code:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <input type="text">
    <script>
        var search = document.querySelector('input');
        // 若使用keydown,按下s后,“s”也会添加到输入框
        // 使用keyup则不会,s键松开后才触发
        document.addEventListener('keyup', function(e) {
     
     
            // console.log(e.keyCode);
            if (e.keyCode === 83) {
     
     
                search.focus();
            }
        });
    </script>

</body>

</html>

Guess you like

Origin blog.csdn.net/Jack_lzx/article/details/109270197
Recommended