<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
#level span{
float: left;
height: 20px;
width: 40px;
border: 1px black solid;
}
</style>
</head>
<body>
<input type="text" id="password">
<div id="level">
<span></span>
<span></span>
<span></span>
</div>
<p id="strength"></p>
<script>
var password = document.getElementById('password');
var level = document.getElementById('level');
var strength = document.getElementById('strength')
// 判断密码组成
var val = password.value
var mode = 0
function aFn(){
if(val.match(/[0-9]/g)){
mode++;
}
if(val.match(/[a-z]/g)){
mode++;
}
if(val.match(/[A-Z]/g)){
mode++;
}
if(val.match(/\W/g)){
mode++;
}
return mode;
}
// 判断密码等级
aFn()
if(val.length<3){
strength.innerText = "密码长度至少4位";
}
if(mode >0 || mode < 2){
level.children[0].style.backgroundColor = "green";
strength.innerText = "低";
}
if(mode > 1 || mode < 3){
level.children[0].style.backgroundColor = "orange";
level.children[1].style.backgroundColor = "orange";
strength.innerText = "中";
}
if(mode > 2){
level.children[0].style.backgroundColor = "red";
level.children[1].style.backgroundColor = "red";
level.children[2].style.backgroundColor = "red";
strength.innerText = "高";
}
</script>
</body>
</html>
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <style> #level span{ float: left; height: 20px; width: 40px; border: 1px black solid; } </style> </head> <body> <input type="text" id="password"> <div id="level"> <span></span> <span></span> <span></span> </div> <p id="strength"></p> <script> var password = document.getElementById('password'); var level = document.getElementById('level'); var strength = document.getElementById('strength') // 判断密码组成 var val = ''; var mode = 0; password.addEventListener('change', function(){// aFn(); val = password.value; if(val.length<3){ strength.innerText = "密码长度至少4位"; }else { if((/[0-9]+/g).test(val)){ mode++; } if((/[a-z]+/g).test(val)){ mode++; } if((/[A-Z]+/g).test(val)){ mode++; } if((/\W+/g).test(val)){ mode++; } // 判断密码等级 if(mode >0 &&mode < 2){ level.children[0].style.backgroundColor = "green"; strength.innerText = "低"; } if(mode > 1 && mode < 3){ level.children[0].style.backgroundColor = "orange"; level.children[1].style.backgroundColor = "orange"; strength.innerText = "中"; } if(mode > 2){ level.children[0].style.backgroundColor = "red"; level.children[1].style.backgroundColor = "red"; level.children[2].style.backgroundColor = "red"; strength.innerText = "高"; }
mode =0 //清空mode } },false); </script> </body> </html>
你这肯定不会执行呀,只会在页面初始化从上往下执行一次,你的把你的校验逻辑加在一个事件中触发,文本框输入事件:onchange 、onkeyup 、onblur看你需求
你把判断密码强度的封装到一个方法中,然后在密码输入时或者完成后 触发 判断密码强度的 方法,这样才可以。
你应该放到keyup事件里