手风琴效果也是业务开发中一个比较常见的效果,类似QQ那样的折叠功能
效果预览
代码实现
- 必要的css
* {margin: 0;padding: 0;}body {height: 100vh;background: linear-gradient(200deg, #ffff00 0%, #ee82ee 100%);overflow: hidden;}ul {list-style: none;}#List {margin: 30px auto;width: 240px;/* border: 1px solid #ccc; */}h2 {background: linear-gradient(241deg, #ffc3ff 0%, #8ec5fc 100%);padding: 10px;cursor: pointer;font-size: 16px;color: #fff;}h2.active {background: linear-gradient(0deg, #9be15d 0%, #00e3ae 100%);}h2 span {margin-right: 10px;}#List ul {display: none;border: 1px solid #8ec5fc;background-color: #fff;}#List > li {border-bottom: #fff 1px solid;cursor: pointer;}#List ul li {padding: 10px;border-bottom: #8ec5fc 1px solid;}#List ul li.l-active{background-color: #9be15d ;color:#fff}
- 静态页面
<ul id="List"><li class="item"><h2><span>▶</span>我的好友</h2><ul><li>张三</li><li>李四</li><li>王五</li><li>赵六</li></ul></li><li class="item"><h2><span>▶</span>我的朋友</h2><ul><li>张三11</li><li>李四22</li><li>王五33</li><li>赵六44</li></ul></li><li class="item"><h2><span>▶</span>我的企业</h2><ul><li>张三11</li><li>李四22</li><li>王五33</li><li>赵六44</li></ul></li></ul>
-
核心逻辑,实现方式多种多样,分别做了尝试,可以选择适合自己思维的方式去做,最终都能出效果
- 方式一:
window.onload = function () {//获取元素let oList = document.getElementById('List')let aItem = oList.getElementsByTagName('li')let aUl = oList.getElementsByTagName('ul')let oH2 = oList.getElementsByTagName('h2')let oSpan = oList.getElementsByTagName('span')let oLi = document.querySelectorAll('.item li')for (var i = 0; i < oH2.length; i++) {oH2[i].index = ioH2[i].onclick = function () {if (this.className == 'active') {for (let j = 0; j < oH2.length; j++) {aUl[j].style.display = 'none'oSpan[j].innerHTML = '▶'oH2[j].className = ''}} else {for (let j = 0; j < oH2.length; j++) {aUl[j].style.display = 'none'oSpan[j].innerHTML = '▶'oH2[j].className = ''}aUl[this.index].style.display = 'block'oSpan[this.index].innerHTML = '▼'oH2[this.index].className = 'active'}}}}// 点击好有名称切换classfor (var i = 0; i < oLi.length; i++) {oLi[i].index = ioLi[i].onclick = function () {//清空所有li的classfor (let j = 0; j < oLi.length; j++) {oLi[j].classList.remove('l-active')}this.classList.add('l-active')}}
- 方式二:
for (let i = 0; i < oH2.length; i++) {oH2[i].index = ioH2[i].isFlag = falseoH2[i].onclick = function () {if (aUl[this.index].isFlag) {for (let j = 0; j < oH2.length; j++) {aUl[j].style.display = 'none'aUl[j].isFlag = falseoSpan[j].innerHTML = '▶'}} else {for (let j = 0; j < oH2.length; j++) {aUl[j].style.display = 'none'aUl[j].isFlag = falseoSpan[j].innerHTML = '▶'}aUl[this.index].style.display = 'block'aUl[this.index].isFlag = trueoSpan[this.index].innerHTML = '▼'}}}
- 方式二:
for (let i = 0; i < oH2.length; i++) {oH2[i].index = ioH2[i].isFlag = falseoH2[i].onclick = function () {if (aUl[this.index].style.display == 'block') {for (let j = 0; j < oH2.length; j++) {aUl[j].style.display = 'none'}} else {for (let j = 0; j < oH2.length; j++) {aUl[j].style.display = 'none'}aUl[this.index].style.display = 'block'}}}