HTML禁止自动填充input表单的解决方案

项目提测中出现问题: 用户名密码自动保存用户名密码之后,回显在项目中别的位置(有密码框,但是没有用户名的地方), 不想让自动显示出来, 需要兼容谷歌, 火狐, IE, 试用了好多方法均不可满足条件,

最后终于找到解决办法,废话不多说,直接上代码!

 

<form method="post" action="">
  <input type="text" name="username" readonly="readonly" id="username">
  <input type="password" name="password" readonly="readonly" id="password">
  <input type="submit" value="登录">
</form>
<script>
  setTimeout(function removeReadonly(){
    var username=document.getElementById("username");
    var password=document.getElementById("password");
    username.removeAttribute("readonly");
    password.removeAttribute("readonly");
  },1000);
</script>

 

思路:首先设置input为只读readonly,当页面加载完成后,浏览器不会自动填充内容,但是也不可以进行编辑。然后我们再用js的定时器延迟一段时间后移除input的只读属性readonly,输入框便可进行再次编辑!完美解决!


原文链接:https://blog.csdn.net/u012800952/article/details/80654649

 

使用以上方法, 是成功阻止了回显问题, 但是经过测试又发现了另一个问题: 页面会出现记住密码的弹窗,显然这样是不对的, 没法去控制用户的行为, 对此bug经过研究,最终切换思路,不阻止自动填充, 让其正常填充, 代码如下:

<div style="opacity:0;">

  <input type="text" name="username">
  <input type="password" name="password">

</div>

最后优化页面样式, 最终完美解决!

 

posted @ 2022-04-12 14:54  wqll  阅读(967)  评论(0编辑  收藏  举报