js添加类名的两种方法

本文介绍了如何通过className和classList属性来添加、删除DOM元素的类名。在聚焦(input.onfocus)和失去焦点(input.onblur)时,演示了如何切换元素的样式,例如添加.active和.active2类以改变边框颜色和阴影。通过调整类名,可以实现不同状态下的样式变化。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.通过className来添加、删除类名

添加类名
获取元素.className = "类名1 类名2 ..."多个类名用空格隔开
移除类名
获取元素名.className = " "直接等于一个空字符串即可删除类名

2.通过classList来添加、删除类名

添加一个类名
获取元素名.classList.add("类名");
添加多个类名用逗号隔开
获取元素名.classList..add("类名1","类名2","类名3",...); 每个类名需要用引号引起来
移除一个类名
获取元素名.classList.remove("类名");
移除多个类名
获取元素名.classList.remove("类名1","类名2","类名3",...); 每个类名需要用引号引起来

举个栗子

在这里插入图片描述

<style>
        input {
            outline: none;
            height: 35px;
            line-height: 35px;
            border: 1px solid #ccc;
            color: #999;
            text-indent: 1rem;
            display: inline-block;
            transition: all .3s;
        }

        .active {
            border: 1px solid skyblue;
            color: #333;
        }

        .active2 {
            box-shadow: 0 0 3px 2px pink;;
        }
    </style>
<input type="text" value="手机">
    <script>
        window.onload = function () {
            document.querySelector('input').onfocus = function () {
                this.value = ""
                // 方法一:
                // this.style.color = "#333"
                // this.style.border = "1px solid skyblue"

                // 方法二:
                this.classList.add("active", "active2");

                // 方法三:
                // this.className = "active active2"
            }
            // trim() 去除空格
            document.querySelector('input').onblur = function () {
                if (this.value.trim() == "") {
                    this.value = "手机"
                    // 方法一:
                    // this.style.color = "#999"
                    // this.style.border = "1px solid #ccc"

                    // 方法二:
                    this.classList.remove("active", "active2");

                    // 方法三:

                    // this.className = ""
                }
            }
        }
    </script>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

吃葡萄不吐葡萄皮嘻嘻

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值