效果预览
预备知识
前边距&后边距
SwiperItem
- SwiperItem 之间是没有间隔的,它们是连接在一起的。
- SwiperItem 的宽度无法更改,只能默认 100%。
计算 previousMargin & nextMargin
数值单位都是 rpx
标题 | |||
---|---|---|---|
原始图片宽度 | 600 | 屏幕总宽度 | 750 |
原始图片两侧剩余宽度 | 750 - 600 = 150 | 单侧剩余宽度 | 150 / 2 = 75 |
previousMargin & nextMargin | 75 |
完整代码
const banners = [
{
src: 'https://fastly.jsdelivr.net/npm/@vant/assets/apple-1.jpeg',
text: '轮播图标题 1'
},
{
src: 'https://fastly.jsdelivr.net/npm/@vant/assets/apple-2.jpeg',
text: '轮播图标题 2'
},
{
src: 'https://fastly.jsdelivr.net/npm/@vant/assets/apple-3.jpeg',
text: '轮播图标题 3'
},
{ src: 'https://fastly.jsdelivr.net/npm/@vant/assets/apple-4.jpeg', text: '轮播图标题 4' }
];
export const CustomSwiper = () => {
const [currentIdx, setCurrentIdx] = useState(0);
const handleSwiperChange = e => {
setCurrentIdx(e.detail.current);
};
return (
<Swiper
className="swiper"
autoplay
circular
previousMargin="75rpx"
nextMargin="75rpx"
onChange={handleSwiperChange}
>
{banners.map((banner, index) => {
return (
<SwiperItem key={banner.src}>
<View className={clsx('swiper__wrap', { active: currentIdx === index })}>
<Image
className="swiper__img"
src={banner.src}
onTap={() => {
console.log(`点击了第${index}张轮播图`);
}}
/>
<View className="swiper__text">{banner.text}</View>
</View>
</SwiperItem>
);
})}
</Swiper>
);
};
.swiper {
width: 100%;
height: 338px;
position: relative;
&__wrap {
width: auto;
height: inherit;
border-radius: 20px;
transform: scale(0.9);
transition: all 0.5s ease;
&.active {
transform: scale(1);
}
}
&__img {
width: 600px;
height: inherit;
border-radius: 20px;
}
&__text {
position: absolute;
bottom: 0;
padding-left: 20px;
box-sizing: border-box;
width: 100%;
height: 78px;
line-height: 78px;
font-weight: 500;
font-size: 32px;
color: #fff;
border-radius: 0px 0px 20px 20px;
background: linear-gradient(180deg, rgba(0, 0, 0, 0) 0%, rgba(0, 0, 0, 0.9) 100%);
}
}