微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

【uniapp】轮播图图片适配

需求:轮播图需要根据图片的大小进行适配,下面的文字跟随轮播图大小进行适配移动

在这里插入图片描述

逻辑

①在swiper里的图片加载完成的时候,@load方法获取图片的宽高,又因为图片的宽高需要适配手机的屏幕,所以需要用uni.getSystemInfoSync()获取可使用窗口的宽度,根据比例计算出图片的高度和swiper的高度
②又因为@load方法无法精准识别下载的图片的顺序,所以第一张图片的适配会出现问题,这个时候,就由后端去识别判断数组里面第一张图片的宽高,再传给前端,然后再进行赋值适配
③@load方法中,将处理过的高度还有对应的index push进一个全新的数组当中,根据数组中的index和对应的index高度去调节swiper的高度

	<swiper class="swiper"
		:indicator-dots="indicatorDots" 
		:current='current'
		:interval="interval" 
		:style="{height:swiperHeight}"
		@change='changeImg'>
			<swiper-item v-for="(item,index) in itemData.data" :key="index" @click="gotoPages(item)" >
				<image :src="item.imgurl" :data-index='index' mode="widthFix" @click="previewImage(index)" @load='handleImg' lazy-load='true' :style="{height:imgList[current]}"></image>
			</swiper-item>
		</swiper>
	data(){
			return{
				indicatorDots: true,
				autoplay: false,
				duration: 500,
				interval: 2000,
				indicatorActiveColor:'#ffffff',
				customBarH:'',
				swiperHeight:'',
				imgList:[] /*图片的高度列表*/,
				current:0
			}
		},
		props:['itemData','height'],
		mounted(){
			this.showImg()
		},
		methods:{
			/*跳转页面*/
			gotoPages(e){
				this.gotoPage(e.linkUrl);
			},
			showImg(){
				this.$nextTick(()=>{
					this.imgList[0]=this.itemData.height
					this.swiperHeight=this.imgList[0]
				})
			},
			handleImg(e){
				 let winWid = uni.getSystemInfoSync().windowWidth;              
				  let imgh = e.detail.height;                
				  let imgw = e.detail.width;
				  let index=e.currentTarget.dataset.index
				  let swiperH = winWid * imgh / imgw +'px'
				  this.imgList[index]=swiperH
				 // this.swiperHeight=swiperH
			},
			changeImg(e){
				this.current=e.detail.current
				this.swiperHeight=this.imgList[this.current]
				
			},
			}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐