赞
踩
- <!DOCTYPE html>
- <html lang="en">
-
- <head>
- <meta charset="UTF-8">
- <meta http-equiv="X-UA-Compatible" content="IE=edge">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <title>Document</title>
- <style>
- *{
- margin:0;
- padding:0;
- }
- body {
- display: flex;
- justify-content: center;
- align-items: center;
- min-height: 100vh;
- box-sizing:border-box;
- }
-
- .green {
- color: green;
- }
-
- .red {
- color: red;
- }
- </style>
- </head>
-
- <body>
- <table>
- <tr>
- <th>用户名</th>
- <td><input type="text" pattern="^[a-zA-Z0-9_-]{4,16}$" data-name="用户名"></td>
- <td><span></span></td>
- </tr>
- <tr>
- <th>密码</th>
- <!-- pattern属性 为input设置正则表达式,配合checkValidity方法验证 -->
- <td><input type="password" pattern="^\w{6,13}$" data-name="密码"></td>
- <td><span></span></td>
- </tr>
- </table>
- <script>
- const ipts = document.querySelectorAll('input');
- const spans = document.querySelectorAll('span');
- let colorFlag = true; //判断颜色
- ipts.forEach((input, index) => {
- input.onblur = function() {
- let iptType = this.getAttribute('data-name');
- if (this.value) {
- //checkValidity()是表单对象方法,用于验证输入是否合法
- if (this.checkValidity()) {
- spans[index].innerText = `${iptType}合法`;
- colorFlag = true;
- } else {
- spans[index].innerText = `${iptType}不合法`;
- colorFlag = false;
- }
- } else {
- spans[index].innerText = `请输入${iptType}`;
- colorFlag = false;
- }
- spans[index].className = colorFlag ? 'green' : 'red';
- }
- })
- </script>
- </body>
-
- </html>

Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。