如何在主要浏览器中禁用特定输入(或表单字段)的自动完成?


当前回答

我通过添加两个假输入并赋予它们绝对位置来阻止Chrome 66自动填充:

<form style="position: relative">
  <div style="position: absolute; top: -999px; left: -999px;">
    <input name="username" type="text" />
    <input name="password" type="password" />
  </div>
  <input name="username" type="text" />
  <input name="password" type="password" />

起初,我尝试添加display:none;但Chrome忽略了这些输入,并自动填充可见的输入。

其他回答

<form name="form1" id="form1" method="post"
      autocomplete="off" action="http://www.example.com/form.cgi">

这将在Internet Explorer和Mozilla Firefox中运行。缺点是它不是XHTML标准。

我尝试了几乎所有的答案,但新版本的Chrome很聪明;如果你写

autocomplete="randomstring" or autocomplete="rutjfkde"

它会自动将其转换为

autocomplete="off"

当输入控件接收到焦点时。

所以,我使用jQuery完成了这项工作,我的解决方案如下。

$("input[type=text], input[type=number], input[type=email], input[type=password]").focus(function (e) {
    $(this).attr("autocomplete", "new-password");
})

这是最简单的,对于表单上的任何数量的控件都可以做到。

如果仅自动完成=“off”不起作用,也可以尝试以下操作:

autocorrect="off" autocapitalize="off" autocomplete="off"

定义输入的属性type=“text”和autocomplete=“off”足以为我关闭自动完成。

除了type=“password”之外,我尝试使用JavaScript钩住别人的建议中的onfocus/onfocuout事件来切换只读属性,效果很好,但当密码字段编辑开始为空时,自动完成密码再次出现。

我建议除了上述工作正常的解决方法之外,还可以使用JavaScript挂钩oninput事件来切换关于密码长度的类型属性。。

<input id="pwd1" type="text" autocomplete="off" oninput="sw(this)" readonly onfocus="a(this)" onfocusout="b(this)" />
<input id="pwd2" type="text" autocomplete="off" oninput="sw(this)" readonly onfocus="a(this)" onfocusout="b(this)" />

和JavaScript。。

function sw(e) {
    e.setAttribute('type', (e.value.length > 0) ? 'password' : 'text');
}
function a(e) {
    e.removeAttribute('readonly');
}
function b(e) {
    e.setAttribute('readonly', 'readonly');
}

除了

autocomplete="off"

使用

readonly onfocus="this.removeAttribute('readonly');"

对于不希望他们记住表单数据(用户名、密码等)的输入,如下所示:

<input type="text" name="UserName" autocomplete="off" readonly 
    onfocus="this.removeAttribute('readonly');" >

<input type="password" name="Password" autocomplete="off" readonly 
    onfocus="this.removeAttribute('readonly');" >