我在做菜单,
单击第一项时,menu pic 1
点击第二项时,menu pic 2
我已经在样式表中为类'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')
})
1条答案
按热度按时间lokaqttq1#
基于你的代码,这里有一个解决方案:
#coloras i see its yourparentcontainer and its haschildrenlet assume they are buttons,you need to select the children usingquerySelectorAlland loop through them,whenever you click on abuttonyou should add**.oncss class toclicked buttonand remove this class from itssiblings**here is workable example: