时间:2022-10-15 10:19:12 | 栏目:JavaScript代码 | 点击:次
功能:
1、点击我的好友会展开下拉出具体的好友
2、再次点击,会折叠内容
3、首次点击某个具体的好友,只有当前这个好友高亮
4、再次点击这个好友时,高亮状态就会消失
主要练习:js绑定事件
慢慢修改小细节:再次点击,会折叠内容时,里面的高亮要全部取消
实现代码
<!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> * { margin: auto; padding: 0px } .content { position: relative; top: 40px; width: 280px; height: auto; border: 1px solid black; margin: 0 auto } span { display: inline-block; border-bottom: 1px dotted grey; width: 100%; background-color: red; } li { padding-left: 20px; list-style: none; } ul { display: none } </style> </head> <body> <div class="box1"> <div class="content"> <div class="cl1"><span> <img src="右箭头.png" alt="" style="width:20px;height:20px;vertical-align: text-bottom;"> 我的好友 </span> <ul> <li>lili</li> <li>zhangsan</li> <li>uncle</li> </ul> </div> <div class="cl1"> <span> <img src="右箭头.png" alt="" style="width:20px;height:20px;vertical-align: text-bottom;">企业好友 </span> <ul> <li>lili</li> <li>zhangsan</li> <li>uncle</li> </ul> </div> <div class="cl1"><span> <img src="右箭头.png" alt="" style="width:20px;height:20px;vertical-align: text-bottom;">黑名单 </span> <ul> <li>lili</li> <li>zhangsan</li> <li>uncle</li> <li>unle</li> <li>une</li> </ul> </div> </div> </div> <script> //点击分组,颜色改变,下面的选项出来 var cls = document.querySelectorAll('span') var uls = document.querySelectorAll('ul') for (i = 0; i < cls.length; i++) { cls[i].addEventListener('click', function() { if (this.flag == 0) { this.style.backgroundColor = 'skyblue' this.children[0].src = '实 向下箭头-01.png' console.log(uls[this.index]); uls[this.index].style.display = 'block' this.flag = 1 } else if (this.flag == 1) { this.style.backgroundColor = 'red' this.children[0].src = '右箭头.png' console.log(uls[this.index]); uls[this.index].style.display = 'none' this.flag = 0 //需要把li全部取消高亮 for (j = 0; j < uls.length; j++) { for (m = 0; m < uls[j].children.length; m++) { uls[j].children[m].style.backgroundColor = 'white' uls[j].children[m].states = 0 } } } }) cls[i].index = i //通过添加一个属性,进行索引 cls[i].flag = 0 } for (i = 0; i < uls.length; i++) { //利用事件冒泡对具体好友绑定点击事件 uls[i].addEventListener('click', function(e) { console.log(e.target); console.log(e.target.states); if (e.target.states == 0) { // this.style.backgroundColor = 'pink'//不能用this,这里的this指向的是uls[i] e.target.style.backgroundColor = 'pink' e.target.states = 1 } else if (e.target.states == 1) { // this.style.backgroundColor = 'pink'//不能用this,这里的this指向的是uls[i] e.target.style.backgroundColor = 'white' e.target.states = 0 } }) console.log(uls[i].children.length); for (j = 0; j < uls[i].children.length; j++) { uls[i].children[j].states = 0 } } ///关键在于第二次重复点击 </script> </body> </html>
需要加索引时,一般说通过自定义属性来设置
可以将该元素视为一个对象,为期添加一个属性,就可以进行索引
另外一种可以在for循环,使用闭包原理
相比,加属性的方法更加方便