最近一直在做通行證項目,里面的注冊模塊中輸入密碼需要顯示密碼強度(低中高)。今天就把做的效果給大家分享下,代碼沒有網上搜索的那么復雜,能夠滿足一般的需求。 
html 代碼如下: 
復制代碼 代碼如下:
 
<!DOCTYPE HTML> 
<html lang="en"> 
<head> 
<meta charset="utf-8"/> 
<title>密碼強度</title> 
<style type="text/css"> 
#passStrength{height:6px;width:120px;border:1px solid #ccc;padding:2px;} 
.strengthLv1{background:red;height:6px;width:40px;} 
.strengthLv2{background:orange;height:6px;width:80px;} 
.strengthLv3{background:green;height:6px;width:120px;} 
</style> 
</head> 
<body> 
<input type="password" maxlength="16"/> 
<div> 
<em>密碼強度:</em> 
<div></div> 
</div> 
</body> 
</html> 
<script type="text/javascript" src="js/passwordStrength.js"></script> 
<script type="text/javascript"> 
new PasswordStrength('pass','passStrength'); 
</script> 
復制代碼 代碼如下:
 
function PasswordStrength(passwordID,strengthID){ 
this.init(strengthID); 
var _this = this; 
document.getElementById(passwordID).onkeyup = function(){ 
_this.checkStrength(this.value); 
} 
}; 
PasswordStrength.prototype.init = function(strengthID){ 
var id = document.getElementById(strengthID); 
var div = document.createElement('div'); 
var strong = document.createElement('strong'); 
this.oStrength = id.appendChild(div); 
this.oStrengthTxt = id.parentNode.appendChild(strong); 
}; 
PasswordStrength.prototype.checkStrength = function (val){ 
var aLvTxt = ['','低','中','高']; 
var lv = 0; 
if(val.match(/[a-z]/g)){lv++;} 
if(val.match(/[0-9]/g)){lv++;} 
if(val.match(/(.[^a-z0-9])/g)){lv++;} 
if(val.length < 6){lv=0;} 
if(lv > 3){lv=3;} 
this.oStrength.className = 'strengthLv' + lv; 
this.oStrengthTxt.innerHTML = aLvTxt[lv]; 
}; 
新聞熱點
疑難解答
圖片精選