禁用Chrome浏览器自动填充表单form的方法

时间:2017-11-06
做项目时一直遇到一个问题,那就是用chrome测试的时候页面上的表单一直会自动填充,并且伴有黄色的背景颜色,有时候感觉很方便,该如何禁止这个行为呢?本文章向大家介绍禁用Chrome浏览器自动填充表单form的方法,需要的朋友可以参考一下。

对于旧版本的Chrome浏览器,我们可以使用以下代码禁止浏览器自动填充:

<form autocomplete="off">

以上代码表示禁止浏览器自动填充form表单。

我们也可以单独设置禁止某一个form元素自动填充,例如:

<input autocomplete="off">

对于新版本的Chrome浏览器,我尝试了两种方法

<form autocomplete="off"><input autocomplete="off">都不起作用,因此我们需要使用其他方法代替。

我使用下面的代码片段来修复它 - 只需要在input password字段的上方添加了另一个文本字段并将其设置display:none

代码类似这样:

<input type="text" name="prevent_autofill" id="prevent_autofill" value="" style="display:none;" />
<input type="password" name="password_fake" id="password_fake" value="" style="display:none;" />
<input type="password" name="password" id="password" value="" />

例外网上看了一下,还可以使用js的方法来 禁止浏览器自动填充,代码如下:

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

将input 设置为只读,当获取焦点时再设置其可读可写。