原理:给按钮添加一个点击事件,对其判断classList对象含不含 click,不含就说明没有展开,那么我们把click给它加入classList,将back给移除。相反包含了click,就是已经展开了,那么再次点击我们需要将其关闭,所以我们移除click,加入back。
click是带有动画的类名,动画的效果是height从0px到500px。
back与之相反,是从500px,到0.
源码:
<!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: 0;
padding: 0;
box-sizing: border-box;
}
body {
display: flex;
justify-content: center;
align-items: center;
}
.contener {
display: flex;
flex-direction: column;
justify-content: center;
margin: 100px;
}
.contener li {
list-style: none;
}
.contener .open {
width: 500px;
height: 60px;
background-image: linear-gradient(315deg, #1fd1f9 0%, #b621fe 74%);
color: antiquewhite;
font-size: 28px;
cursor: pointer;
display: grid;
grid-template-columns: 2fr 3fr;
justify-items: center;
align-items: center;
/* box-shadow: 5px 0px 12px rgba(0, 0, 0, 0.5),
-4px 0px 8px rgba(0, 0, 0, 0.5); */
}
.open img {
width: 24px;
margin-bottom: -12px;
transform: rotateZ(-90deg);
transition: 0.2s ease;
}
.item {
display: none;
overflow: hidden;
}
.contener .item img {
width: 500px;
height: 500px;
object-fit: cover;
object-position: 50% top;
}
/* 对包含click的加入动画 */
@keyframes changeHeight {
from {
height: 0px;
}
to {
height: 500px;
}
}
.contener .click{
animation: changeHeight 0.5s ease-in-out forwards;
}
@keyframes backHeight {
from {
height: 500px;
}
to {
height: 0px;
}
}
.contener .back{
animation: backHeight 0.5s ease-in-out forwards;
}
</style>
</head>
<body>
<ul class="contener">
<li class="open"><img class="down" src="images/下箭头.png"> opne imgOne</li>
<li class="item">
<img src="images/风景照2.jpg" />
</li>
<li class="open"><img class="down" src="images/下箭头.png">open imgeTwo</li>
<li class="item">
<img src="images/风景照3.jpg" />
</li>
<li class="open"><img class="down" src="images/下箭头.png">opne imgeThree</li>
<li class="item">
<img src="images/风景照4.jpg" />
</li>
<li class="open"><img class="down" src="images/下箭头.png">opne imgFour</li>
<li class="item">
<img src="images/风景照5.jpg" />
</li>
<li class="open"><img class="down" src="images/下箭头.png">opne imgFive</li>
<li class="item">
<img src="images/风景照6.jpg" />
</li>
</ul>
</body>
<script>
const openEls = document.querySelectorAll(".open");
const imgs_Down = document.querySelectorAll(".down");
const itemEls = document.querySelectorAll(".item");
for(let i=0;i<itemEls.length;i++){
openEls[i].addEventListener("click", () => {
if(itemEls[i].classList.contains("click")){
itemEls[i].classList.remove("click");
itemEls[i].classList.add("back");
imgs_Down[i].style.transform="rotateZ(-90deg)";
}else{
itemEls[i].style.display = "block";
itemEls[i].classList.add("click");
itemEls[i].classList.remove("back");
imgs_Down[i].style.transform="rotateZ(0deg)";
}
})
}
</script>
</html>
图片我就不放出来了,比较大。