学堂 学堂 学堂公众号手机端

HTML 在网站上禁用密码字段的预测文本

lewis 3年前 (2022-11-11) 阅读数 5 #技术

在网站上禁用密码字段的预测文本,可以通过以下几种方法实现:

1、使用HTML属性autocomplete="off"

在HTML表单中的密码输入框,添加autocomplete="off"属性,可以禁止浏览器自动填充密码。


<form>
  <label for="password">密码:</label>
  <input type="password" id="password" name="password" autocomplete="off">
  <input type="submit" value="提交">
</form>

2、使用JavaScript禁用预测文本

通过JavaScript,可以监听密码输入框的input事件,当输入内容发生变化时,将输入框的值设置为空,从而禁止浏览器自动填充密码。

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF8">
  <meta name="viewport" content="width=devicewidth, initialscale=1.0">
  <title>禁用预测文本</title>
  <script>
    function disablePredictions(input) {
      input.addEventListener('input', function() {
        input.value = '';
      });
    }
  </script>
</head>
<body>
  <form>
    <label for="password">密码:</label>
    <input type="password" id="password" name="password" oninput="disablePredictions(this)">
    <input type="submit" value="提交">
  </form>
</body>
</html>

3、使用CSS禁用预测文本

通过CSS,可以设置密码输入框的outline样式为none,从而禁止浏览器自动填充密码,但这种方法可能不适用于所有浏览器。

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF8">
  <meta name="viewport" content="width=devicewidth, initialscale=1.0">
  <title>禁用预测文本</title>
  <style>
    input[type="password"]:focus {
      outline: none;
    }
  </style>
</head>
<body>
  <form>
    <label for="password">密码:</label>
    <input type="password" id="password" name="password">
    <input type="submit" value="提交">
  </form>
</body>
</html>
版权声明

本文仅代表作者观点,不代表博信信息网立场。

热门