案例:按下s键时光标就自动定位到搜索框

① 核心思路:检测用户是否按下了s键,如果按下了s键,就把光标定位到搜索框里面

② 使用键盘事件对象里面的keyCode判断用户按下的是否是s键

③ 搜索框获得焦点:使用js里面的focus() 方法

<body>
    <input type="text">
    <script>
            var search = document.querySelector('input');
            document.addEventListener('keyup', function(e) {
                // console.log(e.keyCode);
                if (e.keyCode === 83) {
                    search.focus();
                }
            });
    </script>
</body>

猜你喜欢

转载自www.cnblogs.com/zcy9838/p/12940705.html