在小程序或者taro中使用swiper组件的时候,由于swiper有默认高度,使得SwiperItem里面的图片被压缩,mode属性也会失效。
在网上找的最多的一种办法就是动态获取图片高度来设置swiper的高度,这种方法本人感觉不是最优的(主要是代码量还是大的,懒,嘿嘿)。最后经过公司大牛指点获得一个无敌好用的方法解决该问题。
结构:
<View className="father">
<Image className="brother" src={data[0].imgUrl} mode="widthFix" />
<Swiper
className='swiper'
>
{
data.map((item, idx) => {
return (
<SwiperItem>
<Image
src={item.imgUrl}
className='swimg'
mode='widthFix'
lazyLoad
/>
</SwiperItem>
)
}
}
</Swiper>
</View >
scss
.father{
position: relative;
height: auto;
width: 100%;
.brother{
position: relative;
top: 0;
left: 0;
width: 100%;
z-index: 10;
opacity: 0;
}
.swiper{
position: absolute;
top: 0;
left: 0;
height: 100%;
width: 100%;
z-index: 20;
.swimg{
width: 100%;
}
}
}
这样swiper的高就和第一张图片高度一样了,在不设置swiper高度固定值的情况下就可以让swiper里面的图片自适应,非常的方便。
qq:2122375078
b站:行路zfg , UID:345976264