我有一个函数来向单击的标签中添加一个类民用活动。当单击下一个标签时,类自然也会添加到其中。但是我希望类民用活动只在单击的标签上,如果存在的话,将其从以前的和下一个同级中删除。
添加类的代码是
js
var labels = document.getElementsByTagName("label");
for (let i = 0; i < labels.length; i++) {
labels[i].addEventListener("click", addclass);
}
function addclass(event) {
event.target.classList.add("civil-active");
}请建议我该怎么做
发布于 2022-02-04 17:03:33
在事件处理程序中,找到具有类的元素并删除它。
function addclass(event) {
// Those lines will remove the class on the element that has it (if there is one)
let active = document.querySelector(".civil-active")
if(active){
active.classList.remove("civil-active");
}
event.target.classList.add("civil-active");
}https://stackoverflow.com/questions/70989889
复制相似问题