ASCII码 ASCII码

实例演示classList对象和blur事件

发布于:2022-05-07 12:59:10  栏目:技术文档

实例演示classList对象和blur事件

  1. <!DOCTYPE html>
  2. <html lang="zh-CN">
  3. <head>
  4. <meta charset="UTF-8" />
  5. <meta http-equiv="X-UA-Compatible" content="IE=edge" />
  6. <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  7. <title>实例演示classList对象和blur事件</title>
  8. </head>
  9. <style>
  10. .bgc {
  11. background-color: blue;
  12. }
  13. .bgc2 {
  14. background-color: yellow;
  15. }
  16. .active {
  17. color: red;
  18. }
  19. .boder {
  20. border: 1px solid black;
  21. }
  22. .title {
  23. font-size: 60px;
  24. }
  25. </style>
  26. <body>
  27. <h2 class="title">Hello World</h2>
  28. <script>
  29. const h2 = document.querySelector('.title');
  30. // 添加
  31. h2.classList.add('active');
  32. h2.classList.add('bgc');
  33. // 判断
  34. console.log(h2.classList.contains('hello') ? 'hello world' : 'hello php');
  35. // 移除
  36. h2.classList.remove('bgc');
  37. // 替换
  38. h2.classList.replace('active', 'bgc2');
  39. // 动态切换
  40. h2.classList.toggle('boder');
  41. </script>
  42. <!-- 表单非空验证 -->
  43. <form action="" method="post" id="login">
  44. <label for="email">邮箱:</label>
  45. <input type="email" id="email" name="email" value="" autofocus />
  46. <label for="password">密码:</label>
  47. <input type="password" id="password" name="password" />
  48. <!-- 1. type="button" 来表示这是一个普通按钮,没有提交行为 -->
  49. <button type="button" name="submit" onclick="check(this)">登录</button>
  50. </form>
  51. <!-- 表单非空验证 -->
  52. <script>
  53. //点击button触发check函数进行验证
  54. function check(ele) {
  55. // 禁用默认行为
  56. event.preventDefault();
  57. // 防止冒泡
  58. event.stopPropagation();
  59. // 非空验证
  60. // 每一个表单控件input,都有一个form属性,指向所属的表单元素
  61. // 通过form属性可以获取到表单中所有元素的值
  62. let email = ele.form.email;
  63. let password = ele.form.password;
  64. if (email.value.length === 0) {
  65. email.setAttribute('placeholder', '邮箱不能为空,请输入');
  66. email.focus();
  67. return false;
  68. } else if (password.value.length === 0) {
  69. password.setAttribute('placeholder', '密码不能为空,请输入');
  70. password.focus();
  71. return false;
  72. }
  73. }
  74. // 失去焦点验证;
  75. document.forms.login.email.onblur = function () {
  76. if (this.value.length === 0) {
  77. this.setAttribute('placeholder', '不能为空,请输入');
  78. return false;
  79. }
  80. };
  81. </script>
  82. </body>
  83. </html>

相关推荐
阅读 +