JS表单验证:className与classList区别详解

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        span {
            display: inline-block;
            width: 250px;
            height: 30px;
            vertical-align: middle;
            line-height: 30px;
            padding-left: 15px;
        }

        .error {
            color: red;
            background: url(./images/error1.png) no-repeat left center;
        }

        .right {
            color: green;
            background: url(./images/right.png) no-repeat left center;
        }
    </style>
</head>

<body>
    <input type="text">
    <span></span>
    <script>
        const reg = /^[a-zA-Z0-9-_]{6,16}$/
        const input = document.querySelector('input')
        const span = document.querySelector('span')
        input.addEventListener('blur',function () {
            if (reg.test(this.value))
            {
                input.nextElementSibling.innerHTML = "输入正确"
                span.className = 'right'
            }
            else {
                input.nextElementSibling.innerHTML = "请输入6-16位合法字符"
                 span.className = 'error'
            }
        })
    </script>
</body>

</html>

这段表单验证代码中,span.classNamespan.classList.add 这两种操作元素类名方式的区别与联系:

核心区别与联系详解

1. 基本概念与作用
  • 共同点:两者都是用来操作 DOM 元素的 CSS 类名,最终目的都是为元素添加样式类(比如你的代码中的 righterror)。
  • 核心差异
    • className 是直接覆盖元素的整个类名字符串,相当于给元素的 class 属性重新赋值;
    • classList.add()追加一个类名到元素的类列表中,不会覆盖已有的类名。
2. 结合你的代码具体分析

你的代码中使用了 span.className = 'right' / span.className = 'error',这在当前场景下是合理的,因为你只需要给 span 元素设置唯一的类名(要么 right 要么 error)。

我们对比两种写法的效果:

javascript

运行

// 你的写法:直接覆盖,最终 span 只有一个类名
if (reg.test(this.value)) {
  span.className = 'right'; // 覆盖所有类名,span 的 class 变为 "right"
} else {
  span.className = 'error'; // 覆盖所有类名,span 的 class 变为 "error"
}

// 如果用 classList.add:追加类名,可能导致多个类名共存
if (reg.test(this.value)) {
  span.classList.add('right'); // 若之前有 error,span 的 class 变为 "error right"
} else {
  span.classList.add('error'); // 若之前有 right,span 的 class 变为 "right error"
}
3. classList 的完整用法(补充)

因为 classList.add() 是追加,所以如果要实现和 className 一样的 “替换” 效果,需要先移除旧类名:

javascript

运行

if (reg.test(this.value)) {
  span.classList.remove('error'); // 先移除错误类
  span.classList.add('right');    // 再添加正确类
} else {
  span.classList.remove('right'); // 先移除正确类
  span.classList.add('error');    // 再添加错误类
}

// 更简洁的方式:toggle 或 replace
span.classList.replace('error', 'right'); // 直接替换类名(ES6+)
// 或
span.classList.toggle('right', reg.test(this.value)); // 根据条件添加/移除
span.classList.toggle('error', !reg.test(this.value));
4. 适用场景对比
方式特点适用场景
element.className直接覆盖,操作简单元素只需要一个类名,且需完全替换
element.classList精细操作(增 / 删 / 查 / 切换)元素需要多个类名,或按需增删类名

总结

  1. 联系:两者都用于操作 DOM 元素的 CSS 类名,最终都会影响元素的样式;
  2. 核心区别className覆盖式赋值classList.add()追加式添加
  3. 使用建议:你的代码中因为只需要单一类名(right/error 二选一),用 className 是简洁且合理的;如果元素需要多个类名共存(比如同时有 tipright),则优先用 classList(先删后加)。
posted @ 2026-01-09 16:30  chenlight  阅读(2)  评论(0)    收藏  举报  来源