HTML代码
<input type="password" id="password" oninput="checkPasswordStrength()" placeholder="请输入密码">
<table>
<tr id="strength">
<td id="str1"></td>
<td id="str2"></td>
<td id="str3"></td>
</tr>
<br>
<tr>
<td> 弱</td>
<td> 中</td>
<td> 强</td>
</tr>
</table>
CSS 设置尺寸 颜色 默认为灰色 有需要的自己设置尺寸
<style>
#str1{
background-color: darkgrey;
width: 30px;
height: 5px;
border-radius: 5px;
}
#str2{
background-color: darkgrey;
width: 30px;
height: 5px;
border-radius: 5px;
}
#str3{
background-color: darkgrey;
width: 30px;
height: 5px;
border-radius: 5px;
}
</style>
JavaScript代码
<script>
function checkPasswordStrength() {
var password = document.getElementById("password").value; //得到数据
var strength = document.getElementById("strength"); //返回数据
var types = 0;
if (/[a-z]/.test(password)) { //判断是否有a-z
types++;
}
if (/[A-Z]/.test(password)) { //判断是否有A-Z
types++;
}
if (/\d/.test(password)) { //判断是否有数字
types++;
}
if(/\W/.test(password)){ //正则表达式为\w 判断是字母数字下划线,大写W则为没有字母数字的其他字符
types++;
}
switch (types) {
case 1: //没有0 最少是1 必须得输入
document.getElementById("str1").style.backgroundColor='red'
break;
case 2:
document.getElementById("str2").style.backgroundColor='yellow'
break;
default:
document.getElementById("str3").style.backgroundColor='green'
break;
}
}
</script>
效果图
输入AAA
输入AAAbbb
输入AAAbbb...
总结: 用JS改变CSS颜色 正则表达式里面字母大写 变成了“反”则表达式 case循环