先看效果图
点击第一张图片实现折叠,再次点击实现展开
思路
图片容器绑定点击事件获取当前图片索引,触发onTap函数,根据索引判断当前点击的图片是否为第一张,并根据当前的折叠状态来更新每张图片的位置,注意图片向上移动的距离与索引成正相关,而且始终是索引越小层级越大。
代码
<!-- WXML -->
<view class="bigFoldBox">
<view class='foldBox' style='--distance: {{isFold[index]}}px; --z-index: {{zIndex[index]}};' wx:for="{{images0}}" wx:key="index" bindtap='onTap' data-index="{{index}}">
<image src="{{item.src}}" class='image' mode="aspectFit" ></image>
</view>
</view>
/* WXSS */
.bigFoldBox{
width: 100vw;
border-top: calc(1 / 360 * 750rpx) black solid;
}
.image{
width: calc(360 / 360 * 750rpx);
height: calc(125 / 360 * 750rpx);
}
.foldBox {
position: relative;
transform: translateY(var(--distance));
z-index: var(--z-index);
transition: transform 0.5s ease;
}
// JS
data: {
images0: [{src: "https://i0.hdslb.com/bfs/new_dyn/f751c91ef0cdbe8c42bf9c3e088b5d46402122872.jpg@!web-comment-note.avif"},
{src: "https://i0.hdslb.com/bfs/new_dyn/f751c91ef0cdbe8c42bf9c3e088b5d46402122872.jpg@!web-comment-note.avif"},
{src: "https://i0.hdslb.com/bfs/new_dyn/f751c91ef0cdbe8c42bf9c3e088b5d46402122872.jpg@!web-comment-note.avif"},
{src: "https://i0.hdslb.com/bfs/new_dyn/f751c91ef0cdbe8c42bf9c3e088b5d46402122872.jpg@!web-comment-note.avif"},
{src: "https://i0.hdslb.com/bfs/new_dyn/f751c91ef0cdbe8c42bf9c3e088b5d46402122872.jpg@!web-comment-note.avif"}
],
isFold: [],
zIndex: [],
isFolded: true
},
// 点击图片获取索引
onTap(e) {
let index = e.currentTarget.dataset.index;
if (index === 0) {
let newIsFold = this.data.isFolded ?
this.data.isFold.map((value, i) => 0) :
this.data.isFold.map((value, i) => -i * 100);
this.setData({
isFold: newIsFold,
// zIndex: newZIndex, // 不需要更改层级状态
isFolded: !this.data.isFolded, // 更新折叠状态
});
}
}
onLoad: function() {
// 在页面加载时,根据 images0 数组的长度设置 isFold 和 zIndex 数组
let isFold = new Array(this.data.images1.length).fill(0).map((v, i) => -i * 105);
let zIndex = new Array(this.data.images1.length).fill(0).map((v, i) => this.data.images1.length - i);
this.setData({ isFold: isFold, zIndex: zIndex });
},