手风琴模式在网页中偶尔可以见到,下面就来一起实现手风琴。
首先找到 5张图片,在body里放一个背景图片。在body写一个ul>li*5。这里html和css就不具体介绍了直接上图。
实现手风琴主要是js部分。
1.先获取所有li标签,声明下标showIndex。
2遍历li标签使用for循环(var i=0;i<lis.length;i++)
3.给open下标showindex;当触发点击onclick事件,open的类名变为空。点击的this.className=“open”
4将showIndex=lis【i】.index
5.将body背景图替换
实现效果如下:
完整代码发在下面:
body {
height: 100vh;
background-image: url(img/c1.webp);
background-size: cover;
background-position: center;
display: flex;
justify-content: center;
align-items: center;
}
ul {
width: 800px;
height: 400px;
}
li {
width: 80px;
height: 100%;
float: left;
background-size: cover;
background-position: center center;
transition: .3s;
}
.open {
width: 480px;
}
li p {
width: 80px;
height: 100%;
background-color: rgba(255, 255, 255, .5);
color: white;
font-size: 60px;
}
</style>
</head>
<body>
<ul>
<li style="background-image: url(img/c1.webp)" class="open">
<p>寿司全家福</p>
</li>
<li style="background-image: url(img/c2.webp)">
<p>海鲜全家福</p>
</li>
<li style="background-image: url(img/c3.webp)">
<p>炒花蛤</p>
</li>
<li style="background-image: url(img/c4.webp)">
<p>辣白菜</p>
</li>
<li style="background-image: url(img/c5.webp)">
<p>披萨</p>
</li>
</ul>
</body>
<script>
var lis = document.querySelectorAll('li');
var showIndex = 0; //当前open的下标
for (var i = 0; i < lis.length; i++) {
// if (showIndex === this.index) {
// return;
// }
lis[i].index = i; //动态为li添加下标
lis[i].onclick = function() {
// 收起来已经展开的li
// 1.for (var j = 0; j < lis.length; j++) {
// lis[j].className = "";
// }
// 2.动态添加下标
lis[showIndex].className = "";
// 展开点击的li
this.className = "open";
showIndex = this.index;
// 修改body的背景图
document.body.style.backgroundImage = this.style.backgroundImage;
}
}