项目中业务提出了这么一个需求:保留ie记住账号的功能(双击账号栏会出现记住账号列表,填写账号时会智能提示记住账号中符合的账号。都是ie自带的功能),但是不能自动填充密码。最终解决方法丢在了结尾。
百度了下,有大佬总结了不少方案,但是都不能很好地实现:
https://blog.youkuaiyun.com/xw505501936/article/details/52129579
提一下上面这篇文章的其中一个方案:
方案一、密码栏添加属性 autocomplete="off",不生效就改为autocomplete= "new-password" ×
博主用这个方案可以解决,但在我的这个项目中两种写法都不能阻止浏览器自动填充密码,下一个。
方案二、百度到的一些其它的方案,比如添加一个隐藏的form表单、添加隐藏的密码栏 ×
<form style="display: none;">
<input type="password" />
</form>
或者
<input type="password" name="testPwd" id="testPwd" style="width: 0px;height: 0px;float:left"/>
这些方案都只能做到阻止ie浏览器自动填充密码,但是也会使记住密码功能失效(新账号登录时不会再提示是否记住账号密码),不符合需求要求。
方案三、修改readOnly属性,在输入账号时将密码栏readonly设置为true,切换到密码栏时移除readonly属性。 √
这个方案能很接近很接近需求。但是这种效果有个不大不小的毛病,就是密码栏在移除readonly属性后依然是不可输入状态,需要鼠标再点击一次密码栏。原因至今不懂,但我可以尝试用代码模拟再点击一次密码栏的效果。
方案3.1、在密码栏的点击事件中,执行一遍focus方法、click方法。×
都没能解决。
方案3.2、新增一个隐藏的输入栏,点击密码栏时先把焦点跳转到隐藏的输入栏,隐藏的输入栏的onfocus事件中再把焦点跳转回密码栏√
成功实现功能!!
demo代码如下
<!doctype html>
<html>
<head>
<script type="text/javascript">
var testFlag=true;
function testfun(){
testFlag=true;
document.getElementById("loginPwd").setAttribute('readonly','true');
}
function testfunc2(){
document.getElementById("loginPwd").removeAttribute('readonly');
if(testFlag){
document.getElementById("loginPwd2").focus();
}
}
function testfunc3(){
if(testFlag){
testFlag=false;
document.getElementById("loginPwd").focus();
}
}
</script>
<meta charset="utf-8">
<title>无标题文档</title>
</head>
<body>
<form>
<input type="text" id="loginName" name="loginName" onfocus="testfun()"/>
<input type="password" id="loginPwd" name="loginPwd" onfocus="testfunc2()" />
<input type="text" id="loginPwd2" name="loginPwd2" onfocus="testfunc3()" style="width:0px;height:0px;opacity:0" tabindex="-1" />
</form>
</body>
</html>
需要注意隐藏输入栏别放在账号输入框与密码输入框之间,会导致触发不了记住密码功能。