<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <style> * { padding: 0; margin: 0; list-style: none; } ul { margin: auto; display: flex; width: 600px; height: 300px; justify-content: space-between; align-items: center; } ul>li { width: 100px; height: 60px; box-shadow: 0px 0px 10px slateblue; border-radius: 5px; } .on { background-color: slateblue; } </style> </head> <body> <ul> <li></li> <li></li> <li></li> <li></li> <li></li> </ul> </body> <script> /* 如果有同一组元素,我们想要某一个元素实现某种样式, 需要用到循环的排他思想算法: 1. 所有元素全部清除样式(干掉其他人) 2. 给当前元素设置样式 (留下我自己) 3. 注意顺序不能颠倒,首先干掉其他人,再设置自己 */ let oli = document.querySelectorAll('li') //方法一:利用forEach // oli.forEach((item, index) => { // item.addEventListener('click', ev => { // //把所有class清除 // oli.forEach(item => { // item.classList.remove('on') // }) // //给当前节点添加类名 // item.classList.add('on') // }) // }) //方法二:利用for循环 太低级了,别人一下就看出来了不太建议 // for (let index = 0; index < oli.length; index++) { // oli[index].onclick=(() => { // for (let index = 0; index < oli.length; index++) { // oli[index].className = ''; // } // oli[index].className='on' // }) // } //方法三:利用for of 循环 这个最简单 for (let item of oli) { item.onclick = ev => { for (const item of oli) { item.className = '' } item.className = 'on' } } </script> </html>
如果有同一组元素,我们想要某一个元素实现某种样式, 需要用到循环的排他思想算法:
1. 所有元素全部清除样式(干掉其他人)
2. 给当前元素设置样式 (留下我自己)
3. 注意顺序不能颠倒,首先干掉其他人,再设置自己