您可能在网络上看到过很多密码强度指示器的例子。他们让用户知道他们使用的密码很弱,并指出修改后强度如何变化。在本教程中,我们将构建如下所示的密码强度指示器:
让我们从创建密码输入字段和密码强度的 HTML 开始,
稍后我们可以设置样式以直观地表示密码强度:
<div id="password">
<label for="password-input">Password</label>
<input
id="password-input"
name="password-input"
type="password"
required
/>
<div id="password-strength"><span></span></div>
</div>
为了确定密码强度,我们将使用我通过 CDN 包含的zxcvbn JavaScript 库。它也可以作为独立下载和 NPM 包使用:
<script src="https://cdnjs.cloudflare.com/ajax/libs/zxcvbn/4.2.0/zxcvbn.js"></script>
现在对于 JavaScript,首先让我们为密码输入和密码强度定义变量:
const pwd = document.getElementById("password-input");
const pwdStrength = document.getElementById("password-strength");
然后,每次在密码输入字段中添加或删除字符时,我们将使用事件侦听器来检查密码强度:
pwd.addEventListener("input", function () {
const pwdVal = pwd.value;
let result = zxcvbn(pwdVal);
pwdStrength.className += "strength-" + result.score;
});
从返回的分数zxcvbn()在 0 到 4 之间。然后我们将这个分数作为密码强度的一个类添加
,这样我们就可以根据返回的分数应用不同的 CSS 样式。
这就完成了 JavaScript,现在是从密码标签和输入字段开始的 CSS:
#password {
width: 250px;
}
#password label {
display: block;
}
#password-input {
width: 230px;
padding: 10px;
margin: 10px 0 5px 0;
}
现在对于强度指示器,它将显示为浅灰色条带,直到用户开始输入密码:
#password-strength {
height: 5px;
width: 100%;
display: block;
background-color: #ccc;
}
#password-strength span {
display: block;
height: 5px;
border-radius: 2px;
transition: all 500ms ease;
}
剩下要做的就是根据强度得分设置颜色和宽度:
.strength-0 span {
background-color: red;
width: 5%;
}
.strength-1 span {
background-color: orangered;
width: 25%;
}
.strength-2 span {
background-color: orange;
width: 50%;
}
.strength-3 span {
background-color: yellowgreen;
width: 75%;
}
.strength-4 span {
background-color: green;
width: 100%;
}
4K炫酷蓝色科技倒计时