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


当前回答

这对我有用。

<input name="pass" type="password" autocomplete="new-password" />

我们也可以在文本、选择等其他控件中使用此策略

其他回答

为了避免无效的XHTML,可以使用JavaScript设置此属性。使用jQuery的示例:

<input type="text" class="noAutoComplete" ... />

$(function() {
    $('.noAutoComplete').attr('autocomplete', 'off');
});

问题是没有JavaScript的用户将获得自动完成功能。

为了解决这个问题,我使用了一些CSS技巧和以下工作。

input {
    text-security:disc;
    -webkit-text-security:disc;
    -mox-text-security:disc;
}

请阅读本文了解更多详情。

我的问题主要是Chrome自动填充,但我认为这可能比自动完成问题更大。

技巧:使用计时器重置表单并将密码字段设置为空白。100毫秒的持续时间似乎是它工作的最短时间。

$(document).ready(function() {
    setTimeout(function() {
        var $form = $('#formId');
        $form[0].reset();
        $form.find('INPUT[type=password]').val('');
    }, 100);
});

定义输入的属性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”。这样做有一个很好的理由:您希望提供自己的自动完成功能!