我們在開發旅游專題前端時,經常會遇到需要實現飛豬或攜程里面的卡片滑動背景同步切換效果。uni-app 通過 swiper 組件也可以實現類似效果
<view class="swiper-box">
<image class="swiper-bg" :src="cardList[selectedCardIndex]" mode="aspectFill"></image>
<swiper class="swiper"
:previous-margin="cardList.length === 1 ? '20%' : selectedCardIndex === 0 ? '10%' : selectedCardIndex === cardList.length -1 ? '30%' : '20%'"
:next-margin="cardList.length === 1 ? '20%' : selectedCardIndex === cardList.length -1 ? '10%' : selectedCardIndex === 0 ? '30%' : '20%'"
@change="swiperChange">
<swiper-item v-for="(swiperItem,swiperIndex) in cardList" :key="swiperIndex" style="position: relative;">
<image :src='swiperItem' :class="{'swiper-active':selectedCardIndex == swiperIndex}"></image>
</swiper-item>
</swiper>
</view>
css樣式:
page {
background-color: #FAFAFA;
}
.swiper-box {
.swiper-bg {
width: 100%;
position: absolute;
height: 500rpx;
&::after { // 背景圖從上往下漸變效果,慢慢漸變到網頁背景色
content: '';
position: absolute;
z-index: 1;
top: 0;
bottom: 0;
left: 0;
right: 0;
background-image: linear-gradient(to bottom ,transparent, #FAFAFA);
}
}
.swiper {
padding-top: 64rpx;
height: 728rpx; // 考慮到卡片對應圖片大小以及手機分辨率不同,大家可以根據實際情況設置
image {
width: 100%;
height: 100%;
transform: scale(0.78); // 通過縮放實現待選卡片縮小效果
transition: transform 0.3s ease-in-out 0s;
border-radius: 26rpx;
box-shadow: 0px 2rpx 12rpx rgba(0, 0, 0, 0.1);
&.swiper-active {
transform: scale(1);
}
}
}
}
js:
export default {
data() {
return {
selectedCardIndex: 0,
cardList: [
"/static/images/lervor/travel/1.jpg",
"/static/images/lervor/travel/2.jpg"
]
}
},
methods: {
swiperChange(e) {
this.selectedCardIndex = e.detail.current
}
}
}
