您应该绑定一个点击处理程序,并在该点击处理程序内部打开/关闭“活动”类:
document.querySelector("li").addEventListener("click", function () {
this.classList.toggle("active");
});
li.active { background: yellow; }
- Home
如果您有多个这样的li元素:
for (const li of document.querySelectorAll("li")) {
li.addEventListener("click", function () {
this.classList.toggle("active");
});
}
li.active { background: yellow; }
- Home
- Other
如果“活动”类一次只能存在一个li,则:
for (const li of document.querySelectorAll("li")) {
li.addEventListener("click", function () {
const active = document.querySelector("li.active");
this.classList.toggle("active");
if (active && this !== active) active.classList.toggle("active");
});
}
li.active { background: yellow; }
- Home
- Other