实现Instagram登录页密码框按键显示按钮,过滤非有效按键
解决密码框仅在有效按键时显示“显示”按钮的问题
你当前的代码会在任何按键按下时触发按钮显示,包括Shift、Ctrl这类功能键。要实现只在输入字母、数字等密码有效字符时显示按钮,可以通过过滤按键事件的key属性来实现,下面是两种可行的修改方案:
方案一:匹配有效字符(推荐)
通过正则表达式匹配字母、数字,甚至可以包含常见的密码符号,确保只有输入有效密码字符时才显示按钮:
const input = document.querySelector('.password'); const button = document.querySelector('.show-password-btn'); // 确保已获取按钮元素 input.addEventListener('keydown', showButton); function showButton(e) { // 正则可按需调整,此处匹配字母、数字及常见密码符号 const isValidChar = /^[a-zA-Z0-9!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]$/.test(e.key); if (isValidChar) { button.style.display = "block"; } }
如果仅需限制字母和数字,将正则改为/^[a-zA-Z0-9]$/即可。
方案二:排除功能键
直接列出不需要触发的功能键,当按下的键不在排除列表中时显示按钮:
const input = document.querySelector('.password'); const button = document.querySelector('.show-password-btn'); input.addEventListener('keydown', showButton); function showButton(e) { const excludedKeys = ['Shift', 'Alt', 'Control', 'Meta', 'Enter', 'Tab', 'Backspace', 'Delete', 'ArrowUp', 'ArrowDown', 'ArrowLeft', 'ArrowRight', 'CapsLock', 'Escape']; if (!excludedKeys.includes(e.key)) { button.style.display = "block"; } }
注意:需确保已正确获取“显示”按钮的DOM元素,否则会出现未定义错误。
内容的提问来源于stack exchange,提问作者Jatin Rathore
相关产品推荐
相关产品推荐

