求助:实现按下句号/斜杠时跳转至指定CSS类的下一个输入框
实现按句号/斜杠跳转到下一个指定类输入框
我帮你完善了这段脚本,刚好能实现你想要的功能——按下.或/时,自动把焦点移到下一个带userinput类的输入框,完美适配你提到的页面里的IP列输入框:
<script type="text/javascript"> // 监听全局按键事件 window.addEventListener('keydown', function(e) { // 匹配句号(.) 和 斜杠(/) 的keyCode const targetKeyCodes = [190, 191]; if (targetKeyCodes.includes(e.keyCode)) { const currentInput = document.activeElement; // 确保当前焦点在目标输入框内 if (currentInput && currentInput.classList.contains('userinput')) { // 方式1:如果输入框是相邻的,直接取下一个兄弟元素 let nextInput = currentInput.nextElementSibling; // 如果下一个兄弟不是目标输入框,就继续往后找(适配中间有其他元素的情况) while (nextInput && !nextInput.classList.contains('userinput')) { nextInput = nextInput.nextElementSibling; } // 找到有效输入框就跳转焦点 if (nextInput) { nextInput.focus(); e.preventDefault(); // 阻止默认输入行为,避免符号出现在框里 } } } }); </script>
额外优化说明:
- 用
keydown代替keypress:keypress在现代浏览器里对部分按键的支持不如keydown稳定,而且能更好地阻止默认行为 - 增加了遍历逻辑:如果输入框之间有其他元素(比如空格、换行标签),脚本依然能找到下一个目标输入框
- 加入边界判断:避免找不到下一个输入框时出错
如果页面加载完成后脚本才生效有问题,你可以把代码放在DOMContentLoaded事件里,确保所有输入框都加载完毕再绑定监听:
<script type="text/javascript"> document.addEventListener('DOMContentLoaded', function() { window.addEventListener('keydown', function(e) { const targetKeyCodes = [190, 191]; if (targetKeyCodes.includes(e.keyCode)) { const currentInput = document.activeElement; if (currentInput && currentInput.classList.contains('userinput')) { let nextInput = currentInput.nextElementSibling; while (nextInput && !nextInput.classList.contains('userinput')) { nextInput = nextInput.nextElementSibling; } if (nextInput) { nextInput.focus(); e.preventDefault(); } } } }); }); </script>
内容的提问来源于stack exchange,提问作者Eddie
相关产品推荐
相关产品推荐

