实例演示classList对象和blur事件
发布于:2022-05-07 12:59:10
次阅读
实例演示classList对象和blur事件
<!DOCTYPE html><html lang="zh-CN"> <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>实例演示classList对象和blur事件</title> </head> <style> .bgc { background-color: blue; } .bgc2 { background-color: yellow; } .active { color: red; } .boder { border: 1px solid black; } .title { font-size: 60px; } </style> <body> <h2 class="title">Hello World</h2> <script> const h2 = document.querySelector('.title'); // 添加 h2.classList.add('active'); h2.classList.add('bgc'); // 判断 console.log(h2.classList.contains('hello') ? 'hello world' : 'hello php'); // 移除 h2.classList.remove('bgc'); // 替换 h2.classList.replace('active', 'bgc2'); // 动态切换 h2.classList.toggle('boder'); </script> <!-- 表单非空验证 --> <form action="" method="post" id="login"> <label for="email">邮箱:</label> <input type="email" id="email" name="email" value="" autofocus /> <label for="password">密码:</label> <input type="password" id="password" name="password" /> <!-- 1. type="button" 来表示这是一个普通按钮,没有提交行为 --> <button type="button" name="submit" onclick="check(this)">登录</button> </form> <!-- 表单非空验证 --> <script> //点击button触发check函数进行验证 function check(ele) { // 禁用默认行为 event.preventDefault(); // 防止冒泡 event.stopPropagation(); // 非空验证 // 每一个表单控件input,都有一个form属性,指向所属的表单元素 // 通过form属性可以获取到表单中所有元素的值 let email = ele.form.email; let password = ele.form.password; if (email.value.length === 0) { email.setAttribute('placeholder', '邮箱不能为空,请输入'); email.focus(); return false; } else if (password.value.length === 0) { password.setAttribute('placeholder', '密码不能为空,请输入'); password.focus(); return false; } } // 失去焦点验证; document.forms.login.email.onblur = function () { if (this.value.length === 0) { this.setAttribute('placeholder', '不能为空,请输入'); return false; } }; </script> </body></html>
