JavaScript 密碼強度提示效果

admin發表於2019-10-25

分享一個非常簡單的程式碼例項,它實現了簡單的密碼強度檢測效果。

程式碼例項如下:

[HTML] 純文字檢視 複製程式碼執行程式碼
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="author" content="http://www.softwhy.com/" />
<title>螞蟻部落</title>
<style type="text/css">
* {
  margin: 0;
  padding: 0;
}
#password {
  display: inline-block;
  padding: 5px 20px;
  border: 1px solid #c8c8c8;
  color: #333;
}
#password > p {
  font-size: 12px;
  color: #888;
}
.tips {
  display: inline-block;
  padding: 3px 8px;
  border: 1px solid #b9b8b8;
  margin-right: 10px;
}
</style>
<script>
function matchLevel(password) {
  if (password.length < 6) {
    return 0;
  }
  if (password.length >= 6 && password.length < 10) {
    return 1;
  }
  if (password.length >= 10 && password.length < 16) {
    return 2;
  }
  if (password.length >= 16) {
    return 3;
  }
}
window.onload = function() {
  tipColor = ['red', 'yellow', 'orange', 'green'];
  var tipEle = document.getElementsByClassName("tips");
  document.getElementsByTagName("input")[0].onkeyup = function() {
    var level = matchLevel(this.value);
    if (this.value.length) {
      for (var i = 0, eleLen = tipEle.length; i < eleLen; i++) {

        if (i <= level) {
          tipEle[i].style.backgroundColor = tipColor[i];
        } else {
          tipEle[i].style.backgroundColor = '';
        }
      }
    } else {
      for (var i = 0, eleLen = tipEle.length; i < eleLen; i++) {
        tipEle[i].style.backgroundColor = '';
      }
    }
  }
}
</script>
</head>
<body>
  <div id="password">
    密碼:<input type="password" />
    <p>
      密碼強度:
      <span class="tips" level="0"></span>
      <span class="tips" level="1"></span>
      <span class="tips" level="2"></span>
      <span class="tips" level="3"></span>
    </p>
  </div>
</body>
</html>

相關文章