我正在尝试制作这个菜单,
当点击第一项时,菜单PIC 1
当点击第二项时,菜单PIC 2
我已经在样式表中为class 'on'创建了样式。
colorItems = document.querySelector('#color').children[1]
colorItems.children[0].addEventListener('click', () => {
colorItems.children[0].classList.toggle('on')
colorItems.children[1].classList.remove('on')
colorItems.children[2].classList.remove('on')
colorItems.children[3].classList.remove('on')
})
colorItems.children[1].addEventListener('click', () => {
colorItems.children[0].classList.remove('on')
colorItems.children[1].classList.toggle('on')
colorItems.children[2].classList.remove('on')
colorItems.children[3].classList.remove('on')
})
colorItems.children[2].addEventListener('click', () => {
colorItems.children[0].classList.remove('on')
colorItems.children[1].classList.remove('on')
colorItems.children[2].classList.toggle('on')
colorItems.children[3].classList.remove('on')
})
colorItems.children[3].addEventListener('click', () => {
colorItems.children[0].classList.remove('on')
colorItems.children[1].classList.remove('on')
colorItems.children[2].classList.remove('on')
colorItems.children[3].classList.toggle('on')
})
根据您的代码,这里是一个解决方案:
<<p>#颜色/strong>我看到它是你的父容器,它有子容器假设它们是按钮,您需要使用querySelectorAll来选择儿童当你点击按钮时,循环遍历它们你应该在上添加.css类添加到所单击的按钮并从它的兄弟类中删除这个类下面是一个可行的例子:let colorItems = document.querySelectorAll('#color button');
colorItems.forEach(item => {
item.addEventListener('click', ()=> {
colorItems.forEach(i => i != item ? i.classList.remove('on') : i.classList.add('on'));
});
});
.on {
background-color: yellow;
}
<div id="color">
<button>red</button>
<button>blue</button>
<button>white</button>
<button>black</button>
</div>