前端对元素添加 和 删除 类名

如何对元素添加 / 删除类名

1、使用ref

html:
<div class="body" ref="bodyRef"></div>

js代码:
let currentElement = this.$refs.bodyRef;
// 添加类名 active
// currentElement.classList.value += ' active';
currentElement.classList.add("active")
// 删除类名 active
currentElement.classList.remove("active");

2、使用:class

以单个元素为例,如果是多个元素,可用循环,isActive可设置为[false, false]格式,然后绑定index

html: 
<div class="body" :class="{active: isActive}" @click="onClick"></div>

js:
data() {
    
    
	return {
    
    isActive: false};
},
methods: {
    
    
	onClick() {
    
    
		this.isActive = true;
	}
}

猜你喜欢

转载自blog.csdn.net/qq_51741730/article/details/128587618