html5表单验证美化综合案例
程序员文章站
2022-03-26 22:54:06
用到的事件: oninput 在值发生变化时立马触发 oninvalid 在不符合验证的时候触发 onchange 虽然触发值会发生变化,但不是立刻触发,要鼠标失去焦点时才能触发 onfocus 在获得焦点的时候触发 效果图
用到的事件:
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>
上一篇: Android查缺补漏(View篇)--事件分发机制
下一篇: 常用的电脑快捷键【转】