Blogger Information
Blog 15
fans 1
comment 1
visits 174142
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
实例演示classList对象和blur事件非空验证
想做肥仔
Original
802 people have browsed it

一. classList 对象

  1. <style>
  2. .active {
  3. color: aquamarine;
  4. }
  5. .bgc {
  6. background-color: blueviolet;
  7. }
  8. .bgc1 {
  9. background-color: yellow;
  10. }
  11. .em {
  12. color: blueviolet;
  13. }
  14. </style>
  15. <body>
  16. <h1 class="title">Hello World</h1>
  17. <script>
  18. const h1 = document.querySelector('.title');
  19. // class属性获取方法 class属性需要加上Name 才能获取
  20. console.log(h1.className);
  21. // 操作class 属性的值方法 classList
  22. // 添加值操作 add()
  23. h1.classList.add('active');
  24. h1.classList.add('bgc');
  25. // 判读class 内容是否存在 返回 boole 类型的数据 contains()
  26. console.log(h1.classList.contains('active'));
  27. // 移除操作 remove()
  28. h1.classList.remove('bgc');
  29. // 替换操作 replace()
  30. h1.classList.replace('active', 'em');
  31. // 动态切换 class
  32. // 判断 内容 是否存在 不存在就添加 存在就删除
  33. h1.classList.toggle('bgc1');
  34. </script>
  35. </body>

内容示例图

111

二. blur事件非空验证

HTML代码

  1. <!--- onsubmit="return false"从表单禁用提交行为 -->
  2. <form action="" method="post" id="login">
  3. <label class="title">用户登录</label>
  4. <label for="email">邮箱:</label>
  5. <input type="email" id="email" name="email" value="" autofocus />
  6. <label for="password">密码:</label>
  7. <input type="password" id="password" name="password" />
  8. <!--- 1. type="button" 来表示这是一个普通按钮,没有提交行为 -->
  9. <button name="submit" onclick="check(this)">登录</button>
  10. </form>

JS代码

  1. let email = document.forms.login.email;
  2. let password = document.forms.login.password;
  3. function notNull() {
  4. // 禁用默认行为 preventDefault() 这里禁用掉了button
  5. // 阻止冒泡 stopPropagation()
  6. event.preventDefault();
  7. event.stopPropagation();
  8. if (email.value.length === 0) {
  9. alert('喂!邮箱忘了啊!');
  10. return false;
  11. } else if (password.value.length === 0) {
  12. alert('喂!密码忘了啊!');
  13. return false;
  14. } else {
  15. alert('恭喜你通过验证!!!');
  16. }
  17. }
  18. document.forms.login.email.onblur = notNull;
  19. document.forms.login.password.onblur = notNull;

效果示例图

222

Correcting teacher:PHPzPHPz

Correction status:qualified

Teacher's comments:
Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post