4 回答
TA贡献1875条经验 获得超3个赞
您可以使用clickedElem.classList.toggle来切换类。
在此之前,您需要删除除active当前选定按钮之外的类名,如下所示。
const myDemo = (event) => {
const clickedElem = event.target;
console.log(clickedElem);
const allBtns = document.querySelectorAll('.btn.light');
allBtns.forEach(btn => {
if (clickedElem != btn) {
btn.classList.remove('active');
}
});
clickedElem.classList.toggle('active');
}
.active {
background: red;
}
<button onclick="myDemo(event)" class="btn light">DOG</button>
<button onclick="myDemo(event)" class="btn light">DOG</button>
<button onclick="myDemo(event)" class="btn light">DOG</button>
<button onclick="myDemo(event)" class="btn light">DOG</button>
<button onclick="myDemo(event)" class="btn light">DOG</button>
<button onclick="myDemo(event)" class="btn light">DOG</button>
<button onclick="myDemo(event)" class="btn light">DOG</button>
<button onclick="myDemo(event)" class="btn light">DOG</button>
或者反过来,您可以存储之前选择的按钮并使用它。
let previousClicked = null;
const myDemo = (event) => {
const clickedElem = event.target;
if (clickedElem === previousClicked) {
clickedElem.classList.remove('active');
return;
}
if (previousClicked != null) {
previousClicked.classList.remove('active');
}
clickedElem.classList.add('active');
previousClicked = clickedElem;
}
.active {
background: red;
}
<button onclick="myDemo(event)" class="btn light">DOG</button>
<button onclick="myDemo(event)" class="btn light">DOG</button>
<button onclick="myDemo(event)" class="btn light">DOG</button>
<button onclick="myDemo(event)" class="btn light">DOG</button>
<button onclick="myDemo(event)" class="btn light">DOG</button>
<button onclick="myDemo(event)" class="btn light">DOG</button>
<button onclick="myDemo(event)" class="btn light">DOG</button>
<button onclick="myDemo(event)" class="btn light">DOG</button>
TA贡献1853条经验 获得超9个赞
从我在您的函数中看到的情况来看,您似乎还想active从页面中的任何其他按钮中删除该类。这是我的方法:
let activeButton;
const selectButton = e => {
if (activeButton) {
activeButton.classList.remove('active');
}
if (activeButton === e.currentTarget) {
activeButton = null;
return;
}
e.currentTarget.classList.add('active');
activeButton = e.currentTarget;
};
这样它就不必遍历每个按钮来停用它们,因为它会跟踪活动按钮。
TA贡献1811条经验 获得超4个赞
您可以尝试在“myDemo”函数中使用内置切换函数。不要使用 remove(),只需添加以下行:
btn.classList.toggle("active");
TA贡献1866条经验 获得超5个赞
我建议使用classList.toggle().
const myDemo = (event) => {
const clickedElem = event.target;
const allBtns = document.querySelectorAll('.btn.light');
// remove the class from all buttons
allBtns.forEach(btn => btn.classList.remove('active'));
// reapply the class for the button that was clicked
clickedElem.classList.toggle('active');
}
.active {
background: red;
}
<button onclick="myDemo(event)" class="btn light">DOG</button>
<button onclick="myDemo(event)" class="btn light">DOG</button>
<button onclick="myDemo(event)" class="btn light">DOG</button>
添加回答
举报