html代碼:html
1 <form name="form1" action=""> 2 密碼:<input type="password" size="8" onkeyup="pwStrength(this.value)" onblur="pwStrength(this.value)"> 3 <br> 4 密碼強度: 5 <table width="220px" border="1" cellspacing="0" cellpadding="1" bordercolor="#eeeeee" height="22px"> 6 <tr align="center" bgcolor="#f5f5f5"> 7 <td width="33%" id="strength_L">弱</td> 8 <td width="33%" id="strength_M">中</td> 9 <td width="33%" id="strength_H">強</td> 10 </tr> 11 </table> 12 </form>
js代碼:this
1 function pwdStrength(pwd) { 2 O_color = "#eeeeee"; 3 L_color = "#FF0000"; 4 M_color = "#FF9900"; 5 H_color = "#33CC00"; 6 var level = 0, strength = "O"; 7 if (pwd == null || pwd == '') { 8 strength = "O"; 9 Lcolor = Mcolor = Hcolor = O_color; 10 } 11 else { 12 var mode = 0; 13 if (pwd.length <= 4) 14 mode = 0; 15 else { 16 for (i = 0; i < pwd.length; i++) { 17 var charMode, charCode; 18 charCode = pwd.charCodeAt(i); 19 // 判斷輸入密碼的類型 20 if (charCode >= 48 && charCode <= 57) //數字 21 charMode = 1; 22 else if (charCode >= 65 && charCode <= 90) //大寫 23 charMode = 2; 24 else if (charCode >= 97 && charCode <= 122) //小寫 25 charMode = 4; 26 else 27 charMode = 8; 28 mode |= charMode; 29 } 30 // 計算密碼模式 31 level = 0; 32 for (i = 0; i < 4; i++) { 33 if (mode & 1) 34 level++; 35 mode >>>= 1; 36 } 37 } 38 switch (level) { 39 case 0: 40 strength = "O"; 41 Lcolor = Mcolor = Hcolor = O_color; 42 break; 43 case 1: 44 strength = "L"; 45 Lcolor = L_color; 46 Mcolor = Hcolor = O_color; 47 break; 48 case 2: 49 strength = "M"; 50 Lcolor = Mcolor = M_color; 51 Hcolor = O_color; 52 break; 53 default: 54 strength = "H"; 55 Lcolor = Mcolor = Hcolor = H_color; 56 break; 57 } 58 } 59 document.getElementById("strength_L").style.background = Lcolor; 60 document.getElementById("strength_M").style.background = Mcolor; 61 document.getElementById("strength_H").style.background = Hcolor; 62 return strength; 63 }