我正在构建一个菜单栏,其中包含当前用户点击时突出显示的类。
如果有人点击li,它会从之前的li中删除并将其放在点击的新li上?
这是我的代码
li.forEach(li => {
li.addEventListener('click', () => {
li.classList.add("selected");
li.style.background = '';
li.style.paddingTop = '';
});
});
答案 0 :(得分:1)
你可以做这样的事情
li.forEach(li => {
li.addEventListener('click', () => {
removeClass();
li.classList.add("selected");
li.style.background = '';
li.style.paddingTop = '';
});
});
function removeClass () {
li.forEach(li => {
li.classList.remove("selected");
})
}
答案 1 :(得分:0)
这个怎么样
items.forEach(li => {
li.addEventListener('click', () => {
items.forEach(li => li.classList.remove("selected"));
li.classList.add("selected");
li.style.background = '';
li.style.paddingTop = '';
});
});
答案 2 :(得分:0)
一个简单的方法如下:
li.forEach(li => {
li.addEventListener('click', () => {
// find the parent-node of the current <li> element:
li.parentNode
// use Element.querySelector() to find the current
// <li> element with the 'selected' class:
.querySelector('li.selected')
// use classList.remove() to remove that class-name:
.classList.remove('selected');
// as before:
li.classList.add("selected");
// why is the following necessary? It *seems* to be
// undoing something that shouldn't be necessary:
li.style.background = '';
li.style.paddingTop = '';
});
});
参考文献: