代碼如下(大佬勿噴):
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>test</title> <style type="text/css"> div{ text-align: center; margin-top: 100px;} input{ color: #000; outline: none;} .span{ font-size: 14px; color: #999999; margin: 0 0 0 10px; user-select: none;} .wrong{ color: red;} .right{ color: green;} </style> </head> <body> <div> <input type="text" /> <span class="span">* 請輸入6~16位密碼</span> </div> <script> // 1. 獲取元素 var input = document.querySelector("input"); var span = document.querySelector("span"); // 2. 注冊事件 失去焦點 input.onblur = function(){ // 根據表單里面值得長度 input.value.length if (this.value.length <6 || this.value.length >16){ span.innerHTML = "× 輸入錯誤,請重新輸入!"; span.className = "span wrong"; }else{ span.innerHTML = "√ 輸入正確"; span.className = "span right"; } } </script> </body> </html>