如何检测浏览器是否自带「显示密码」功能以隐藏自定义按钮?
如何检测浏览器是否自带「显示密码」功能以隐藏自定义按钮?
这个问题我之前也帮人捋过,确实不想页面上两个显示密码的眼睛按钮凑在一起,显得冗余又奇怪😅。其实不用去硬判断浏览器型号(毕竟UA可以伪造,版本更新也快),用特征检测的方式最靠谱——直接检测浏览器本身是否自带这个内置功能。
这里有个实用的检测函数,你可以直接用:
function hasBuiltInPasswordToggle() { // 创建一个临时的隐藏密码输入框,避免影响页面布局 const tempInput = document.createElement('input'); tempInput.type = 'password'; tempInput.style.position = 'absolute'; tempInput.style.opacity = '0'; tempInput.style.pointerEvents = 'none'; document.body.appendChild(tempInput); // 检测不同浏览器的内置控件特征:IE/Edge用::-ms-reveal,Chrome/新版Edge用::-webkit-reveal const supportsMsReveal = window.getComputedStyle(tempInput, '::-ms-reveal').display !== 'none'; const supportsWebkitReveal = window.getComputedStyle(tempInput, '::-webkit-reveal').display !== 'none'; const hasDefaultToggle = supportsMsReveal || supportsWebkitReveal; // 用完临时元素记得删掉,避免污染DOM document.body.removeChild(tempInput); return hasDefaultToggle; }
调用这个函数的逻辑很简单:如果检测到浏览器自带显示密码功能,就把你自定义的按钮隐藏起来:
const customToggle = document.getElementById('your-custom-password-toggle'); if (hasBuiltInPasswordToggle()) { customToggle.style.display = 'none'; }
需要注意的是,不同浏览器对内置控件的伪元素命名可能有差异,上面的代码覆盖了目前主流的Chrome、Edge、IE等浏览器的情况。要是担心某些小众浏览器没覆盖到,也可以反过来处理——默认显示自定义按钮,只有检测到内置功能时才隐藏,这样兼容性会更稳妥。
备注:内容来源于stack exchange,提问作者Sharon
相关产品推荐
相关产品推荐

