博主信息
博文 47
粉丝 1
评论 0
访问量 54268
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
演示classList对象与使用blur进行非空验证
新手1314
原创
592人浏览过

演示classList

1.classList.add():用js加上class样式。

  1. <style>
  2. .active{
  3. color:red;
  4. }
  5. </style>
  6. <h2 class="title" id="one">新手1314</h2>
  7. <script>
  8. const h2 = document.querySelector(".title");//找到h2
  9. h2.classList.add("active");
  10. </script>
  11. 结果:新手1314的字体变为红色。

2.classList.contains():判断有无class样式。

  1. <style>
  2. .active{
  3. color:red;
  4. }
  5. </style>
  6. <h2 class="title" id="one">新手1314</h2>
  7. <script>
  8. const h2 = document.querySelector(".title");
  9. h2.classList.add("active");
  10. console.log(h2.classList.contains("active"));
  11. </script>
  12. 结果:true

3.classList.remove():移除class样式。

  1. <style>
  2. .active{
  3. color:red;
  4. }
  5. .backg{
  6. background-color: aquamarine;
  7. }
  8. </style>
  9. <h2 class="title" id="one">新手1314</h2>
  10. <script>
  11. const h2 = document.querySelector(".title");
  12. h2.classList.add("active");
  13. h2.classList.add("backg");
  14. h2.classList.remove("backg");
  15. </script>
  16. 结果:h2的样式里只有active的样式,背景颜色被移除

4.classList.replace(“被替换样式”,”替换的样式”)。

  1. <style>
  2. .active{
  3. color:red;
  4. }
  5. .list{
  6. color:violet;
  7. }
  8. </style>
  9. <h2 class="title" id="one">新手1314</h2>
  10. <script>
  11. const h2 = document.querySelector(".title");
  12. h2.classList.add("active");
  13. h2.classList.replace("active","list");
  14. </script>
  15. 结果:新手1314的字体颜色由红色变为紫罗兰色。

5.classList.toggle():动态切换class(有样式的话去除样式,没样式的话添加样式)

  1. <style>
  2. .backg{
  3. background-color:aquamarine;
  4. }
  5. </style>
  6. <h2 class="title" id="one">新手1314</h2>
  7. <script>
  8. const h2 = document.querySelector(".title");
  9. h2.classList.toggle("backg");
  10. </script>
  11. 结果:背景颜色变为青色。(如果前面多加h2.classList.add("backg");的话结果为去掉背景色。)

使用blur进行非空验证

js代码:

  1. <script>
  2. document.forms.login.email.onblur = function () {
  3. if (this.value.length === 0) {
  4. alert("邮箱不能为空");
  5. return false;
  6. } else if (this.value.length !== 0 && password.value.length !== 0) {
  7. alert("验证通过");
  8. }
  9. };
  10. document.forms.login.password.onblur = function () {
  11. if (this.value.length === 0) {
  12. alert("密码不能为空");
  13. return false;
  14. } else if (this.value.length !== 0 && email.value.length !== 0) {
  15. alert("验证通过");
  16. }
  17. };
  18. </script>
批改老师:PHPzPHPz

批改状态:合格

老师批语:
本博文版权归博主所有,转载请注明地址!如有侵权、违法,请联系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+教程免费学