Claim:
There is an input box, when the user presses the s
key, the cursor is automatically positioned in the input box.
Realization ideas:
- Check whether the user has pressed the
s
key, if the key is presseds
, the cursor is positioned in the search box - Use the keyboard event object to
keyCode
determine whether the user pressed the s key - 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>