今天写登录界面的输入框时输入框时,发现一个问题。
我的登录界面两个输入框的大体代码如下:
<input type="text" name="username" class="input-text" placeholder="username"/>
<input type="password" name="password" class="input-text" placeholder="password"/>
理想的打开登录界面的效果图如下:

如果浏览器保存了表单用户名和密码的话,打开界面的时候效果图如下:

这时候也把浏览器自带的样式取消,百度了一波,最后的解决方案如下:
<input type="text" name="username" AUTOCOMPLETE="off" class="input-text" placeholder="username"/>
<input type="text" name="password" AUTOCOMPLETE="off" class="input-text" onfocus="this.type='password'" placeholder="password"/>
主要是这两个属性:AUTOCOMPLETE="off"和type="text" οnfοcus="this.type='password'"。一般的type="text"的input可以采用AUTOCOMPLETE="off"解决。W3C对autocomplete的属性描述如下:
autocomplete 属性规定输入字段是否应该启用自动完成功能。自动完成允许浏览器预测对字段的输入。当用户 在字段开始键入时,浏览器基于之前键入过的值,应该显示出在字段中填写的选项 。
既然type="text"的问题解决了,type="password"的问题其实也可以借鉴它,我们初始化的时候让type="text",并设置AUTOCOMPLETE="off",当input聚焦时,把type从text转化为password。一般表单填充只有初始化的时候,只要我们在初始化的时候转化为text就可以解决问题了。
补充(上述方法效果,可以试试以下方法):
//搜索框
<input type="text" autocomplete="off" >
//下面是额外加的标签
<input type="password" autocomplete="new-password" style="display: none"/>
autocomplete="off"很有可能不能单独使用,要和autocomplete="new-password"结合起来使用才有效果。
参考文献:
本文介绍如何通过HTML属性禁用浏览器自动填充表单字段,并提供了解决方案,包括使用autocomplete属性的不同值组合。

1508

被折叠的 条评论
为什么被折叠?



