博主信息
博文 29
粉丝 0
评论 0
访问量 26577
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
ClassList对象学习总结、表单事件非空验证
千里马遇伯乐
原创
741人浏览过

ClassList对象实践

1. 给出一个h2

HTML

  1. <h2 class="title">测试</h2>

添加css样式

  1. <style>
  2. .title {
  3. background-color: green;
  4. color: rgb(244, 246, 248);
  5. }
  6. .title1 {
  7. background-color: rgb(18, 26, 150);
  8. }
  9. .title2{
  10. color:chartreuse;
  11. }
  12. .title3 {
  13. background-color: orange;
  14. color:burlywood;
  15. }
  16. </style>

效果

为h2添加一个叫‘title1’的类名从而改变它的样式后效果

  1. const h2=document.querySelector('.title')
  2. // classlist.add()添加类名
  3. h2.classList.add('title1');

判断h2是否包含其他类名

  1. // clsslist.contains():判断是是否包含
  2. console.log(h2.classList.contains('title1'));//显示true
  3. console.log(h2.classList.contains('title3'));//显示false

删除类名

  1. // classlist.remove()删除类名
  2. h2.classList.remove('title');
  3. console.log(h2.classList.contains('title'));

替换类名

  1. // classlist.replace()替换类名
  2. h2.classList.replace('title1','title');
  3. console.log(h2.classList.contains('title'));
  4. console.log(h2.classList.contains('title1'));

动态添加类名

  1. // classlist.toggle()动态切换css
  2. // 如果之前没有这个样式,就自动添加,如果有,则去掉这个样式
  3. console.log(h2.classList.contains('title'));//显示true
  4. h2.classList.toggle('title');
  5. console.log(h2.classList.contains('title'));//显示false
  6. console.log(h2.classList.contains('title3'));//显示false
  7. h2.classList.toggle('title3');
  8. console.log(h2.classList.contains('title3'));//显示true

失去焦点时进行非空验证

  1. <body>
  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>
  11. <script>
  12. function check(ele) {
  13. // 禁用默认行为
  14. event.preventDefault();
  15. // 防止冒泡
  16. event.stopPropagation();
  17. // 非空验证
  18. let email = ele.form.email;
  19. let password = ele.form.password;
  20. if (email.value.length === 0) {
  21. alert('邮箱不能为空');
  22. email.blur();
  23. return false;
  24. } else if (password.value.length === 0) {
  25. alert('密码不能为空');
  26. password.blur();
  27. return false;
  28. } else {
  29. alert('验证通过');
  30. }
  31. }
  32. document.forms.login.email.onblur = function() {
  33. if (this.value.length === 0) {
  34. alert('不能为空');
  35. return false;
  36. }
  37. }
  38. </script>
  39. </body>

本博文版权归博主所有,转载请注明地址!如有侵权、违法,请联系admin@php.cn举报处理!
全部评论 文明上网理性发言,请遵守新闻评论服务协议
0条评论
作者最新博文
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号

  • 登录PHP中文网,和优秀的人一起学习!
    全站2000+教程免费学