当前位置:网站首页>原生JS动态添加和删除类
原生JS动态添加和删除类
2022-06-22 10:14:00 【zh阿飞】
原生JS动态添加和删除类
由于需要, 给按钮组监听点击事件(要求用事件委托),当有一个按钮被点击时,相应的给该按钮添加一个类(激活类),其他没有点击的按钮就要移出该类
添加和删除类有三种方法
首先得到一个 dom 对象(也叫dom元素), 通过document.getElement……的几种方法得到
如
<div id="box" class="foo"></div>
==>
<div id="box" class="foo bar"></div>
let el = document.getElementById("box");
通过类名, 获取类名:
el.className, 赋值:el.className = "foo bars"会覆盖掉原来的类通过属性,获取类名:
el.getAttribute("class");赋值:el.setAttribute("class", "foo bar");会覆盖掉原来的类通过属性节点
attributeNode(性能差一点,但能兼容ie,getAttribute()ie 的有些版本不支持 )setAttributeNode()方法向元素中添加指定的属性节点。
如果这个指定的属性已存在,则此方法会替换它。,获取类名:getAttributeNode("class").value, 赋值:let attr = document.createAttribute("class"); attr.nodeValue = "foo bar"; el.setAttributeNode(attr)通过 classList属性, 获取类名
el.classList;追加类名:el.classList.add("foo");删除类 :el.calssList.remove("foo");
上边四种方法, classList最灵活,最好好用, 但是不支持 ie9 以下的浏览器, 兼容性要差一些
示例代码:
html
<div id="btn-group">
<div class="btn btn-active">按钮1</div>
<div class="btn">按钮2</div>
<div class="btn">按钮3</div>
<div class="btn">按钮4</div>
</div>
js代码, 其中用到了ES6语法(用ES6写简洁)
let myEventUtil = {
// 添加监听事件
addEvent (element, type, handler) {
if (element.addEventListener) {
element.addEventListener(type, handler, false);
} else if (element.attach){
// ie
element.attach("on"+ type, handler);
} else {
element['on' + type] = handler;
}
},
getTarget (event) {
let event = event || window.event;
return event.target || event.srcElement;
}
}
let my$ = id => document.getElementById(id);
let btnGroup = my$(“btn-group”);
myEventUtil.addEvent(btnGroup, 'on', function (ev) {
// 给所有的 btn 都移除激活的类 btn-active
// console.log(this) ==> 是一个dom元素 btnGroup
// 可以通过 el.children[i]拿到具体的子元素
// 拿到子元素了可以通过 el.classList.remove("className") 删除类
// el.classList.add("className") 来添加类
// 删除类
let len = this.children.length;
for (let i = 0; i < len; i ++) {
this.children[i].classList.remove("btn-active");
// this.children[i].className = "btn"; // 用其中一个就行
}
// 添加类, 拿到具体的 btn 给它添加类
myEventUtil.getTarget(ev).classList.add("btn-active");
// myEventUtil.getTarget(ev).className = "btn"; // 用其中一个就行
});
边栏推荐
- Software engineering topics
- 一句话木马上传常见的几种方法
- 6-32 construction of linked list by header insertion method
- The future of Dao: an organization primitive for building Web3
- Pareto's law at work: focus on results, not outputs
- 使用 Matplotlib 这么久,竟不知道数据可以动起来
- [popular science] to understand supervised learning, unsupervised learning and reinforcement learning
- TCP 拥塞识别
- How harmful is the code signature certificate once it is leaked
- Learning serialization and deserialization from unserialize3
猜你喜欢

软件项目管理 8.3.敏捷项目质量活动

Tiktok practice ~ one click registration and login process of mobile phone number (verification code)

数据智能基础设施升级窗口将至?看九章云极 DingoDB 如何击破数据痛点

Opencv人脸识别之发送QQ邮箱

Quickly master asp Net authentication framework identity - login and logout

Ctfshow Web Learning Records

From in MySQL_ Unixtime and UNIX_ Timestamp processing database timestamp conversion - Case

Former amd chip architect roast said that the cancellation of K12 processor project was because amd counseled!

【科普】一文弄懂监督式学习、非监督式学习以及强化式学习

Byte 2: why is the key of the redis master node expired, but the expired data is still read from the secondary node? How to solve it?
随机推荐
Niuke.com Huawei question bank (31~40)
What kind of experience is middle-aged unemployment
Zuckerberg's latest VR prototype is coming. It is necessary to confuse virtual reality with reality
Web Configuration of Visual Studio Code
10-2xxe vulnerability principle and case experiment demonstration
使用 Matplotlib 这么久,竟不知道数据可以动起来
【科普】一文弄懂监督式学习、非监督式学习以及强化式学习
信息系统项目典型生命周期模型
呼叫中心CTI系统
三个月让软件项目成功“翻身”!
字节三面:到底知不知道什么是Eureka?
Vs2022 connecting to SQLSERVER database tutorial
Three months to successfully "turn over" the software project!
xlrd.biffh.XLRDError: Excel xlsx file; not supported 解决办法
快速掌握 ASP.NET 身份认证框架 Identity - 登录与登出
From in MySQL_ Unixtime and UNIX_ Timestamp processing database timestamp conversion - Case
网络中connect的作用
Start from the principle of MVC and knock on an MVC framework to bring you the pleasure of being a great God
Software project management 8.3 Agile project quality activities
It is said that the price of the iPhone 14 will rise; TikTok US user data is transferred to Oracle, and bytes cannot be accessed; Seatunnel 2.1.2 releases geek headlines