博客列表 >js-基础(五)classList对象、blur事件进行表单非空验证

js-基础(五)classList对象、blur事件进行表单非空验证

Technology has temperature
Technology has temperature原创
2022年04月26日 11:47:15701浏览

1.classList对象

  1. const box = document.querySelector(".box");
  2. //parseInt()字符串转换为数字
  3. //window.getComputedStyle()全局方法获取计算样式(内部样式和外部样式)
  4. let borderWidth = parseInt(window.getComputedStyle(box).borderWidth) + 5;
  5. box.style.borderWidth = borderWidth + "px";
  6. //添加
  7. box.classList.add("backgroundColor");
  8. //判断
  9. console.log(box.classList.contains("backgroundColor"));
  10. //移除
  11. box.classList.remove("backgroundColor");
  12. //替换('旧值','新值')
  13. box.classList.replace("box", "borderChange");
  14. //切换,类名有则移除,没有则添加
  15. box.classList.toggle("colorChange");
  16. box.classList.toggle("borderChange");

2.blur事件进行表单非空验证

  1. function check(element) {
  2. //禁用默认行为
  3. event.preventDefault();
  4. //阻止冒泡
  5. event.stopPropagation();
  6. let email = element.form.email;
  7. let password = element.form.password;
  8. if (email.value.length === 0) {
  9. alert("邮箱为空");
  10. email.focus();
  11. return false;
  12. } else if (password.value.length === 0) {
  13. alert("密码为空");
  14. password.focus();
  15. return false;
  16. } else {
  17. return true;
  18. }
  19. }
  20. //blur失去焦点时触发
  21. document.forms.login.email.onblur = function () {
  22. if (this.value.length === 0) {
  23. alert("邮箱不能为空");
  24. return false;
  25. }
  26. };
  27. document.forms.login.password.onblur = function () {
  28. if (this.value.length === 0) {
  29. alert("密码不能为空");
  30. return false;
  31. }
  32. };
声明:本文内容转载自脚本之家,由网友自发贡献,版权归原作者所有,如您发现涉嫌抄袭侵权,请联系admin@php.cn 核实处理。
全部评论
文明上网理性发言,请遵守新闻评论服务协议