用到的事件: oninput 在值發生變化時立馬觸發 oninvalid 在不符合驗證的時候觸發 onchange 雖然觸發值會發生變化,但不是立刻觸發,要滑鼠失去焦點時才能觸發 onfocus 在獲得焦點的時候觸發 效果圖 <!DOCTYPE html> <html lang="en"> <hea ...
用到的事件:
oninput 在值發生變化時立馬觸發
oninvalid 在不符合驗證的時候觸發
onchange 雖然觸發值會發生變化,但不是立刻觸發,要滑鼠失去焦點時才能觸發
onfocus 在獲得焦點的時候觸發
效果圖
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>form</title> <style> .container{margin:100px;font-size:14px;position: relative;} .item{position: relative;width:250px;height:40px;} input,select{width:250px;height:20px;line-height:20px;border-radius: 4px;border:1px solid #999;color:#999;margin-bottom:10px;padding:5px;position: absolute;left:66px;} .item label{position: absolute;left:0;top:5px;} select{height:30px;width:260px;} input[type=submit]{height:30px;line-height:20px;position:absolute;left:0;} input:required,select:required{background:url(img/star.jpg) 90% center no-repeat;} input:required:valid,select:required:valid{background:url(img/right.png) 90% center no-repeat;box-shadow:0 0 5px green;border:1px solid green;} input:focus:invalid,select:focus:invalid{background:url(img/error.png) 90% center no-repeat;box-shadow:0 0 5px red;border:1px solid red;} </style> </head> <body> <div class="container"> <form action="#"> <div class="item"> <label for="tel">手機號</label> <input type="tel" id="tel" placeholder="請輸入手機號碼" required pattern="^1[0-9]{10}$" oninput="this.setCustomValidity('')" oninvalid="this.setCustomValidity('請輸入正確手機號哈')"> </div> <div class="item"> <label for="password">密碼</label> <input type="password" id="password" placeholder="6-20位" required pattern="^[a-zA-Z0-9]\w{5,19}$" oninput="this.setCustomValidity('')" oninvalid="this.setCustomValidity('請輸入正確密碼哈')" onchange="checkPwd()"> </div> <div class="item"> <label for="repassword">確認密碼</label> <input type="password" id="repassword" placeholder="確認密碼" required oninput="this.setCustomValidity('')" oninvalid="this.setCustomValidity('請輸入正確密碼哈')" onchange="checkPwd()"> </div> <div class="item"> <label for="choose">瞭解方式</label> <select name="choose" id="choose" required> <option value="">--請選擇--</option> <option value="">選項一</option> <option value="">選項二</option> <option value="">選項三</option> </select> </div> <input type="submit" value="提交"> </form> </div> <script> function checkPwd(){ if(password.value != repassword.value){ repassword.setCustomValidity("兩次密碼輸入不一致哎"); }else{ repassword.setCustomValidity(""); } } </script> </body> </html>