uniApp swiper内部图片高度自适应

解决uniApp中swiper组件默认高度导致图片显示不全的问题,通过动态获取图片最大高度,实现swiper自适应内容高度。利用$u.getRect获取dom元素高度,找到最高图片并设置swiper高度。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

因为uniApp swiper组件有默认高度的150px 

这时如果图片大于150px就会显示不完整,导致很丑的样式问题。

我们希望外部的swiper 自适应内部的图片组中 高度最高的图片 怎么办?

1.先获取内部图片所有dom的元素样式 数组

2.对数组按照高度进行排列 取出高度最高的值

3.将swiper 使用:style 动态绑定最大高度

<!-- 轮播图 -->
            <--SwiperHeight 是通过计算后得到的高度值-->
			<swiper class="swiper" :style="`height:${SwiperHeight}rpx`" :indicator-dots="false" :autoplay="false"
				:interval="interval" :duration="duration">
				<swiper-item v-for="(item,i) of bannerImags.result" :key="item.id">
					<view class="top-header-swiper">
						<!-- 图片懒加载 给一个类名用于查找dom-->
                        <u-lazy-load class="get_image_height" :image="item.imgUrl"/>
					</view>
				</swiper-item>
			</swiper>
//封装一个方法 用于动态获取内部图片最大的高度

//获取dom数组中高度最大值并返回
async function GetDomMaxHeight(targetClass) {
	try{
		if (targetClass) {
			//规定传入class 不需要加. 默认查询所有 
			let rectInfo = await _this.$u.getRect('.' + targetClass, true);
			if (rectInfo?.length > 0) {
				console.log(rectInfo ,'????')
				let MaxHeight = rectInfo.map(xitem => xitem.height).sort((a, b) => b - a)[0];
				return MaxHeight
			} else {
				console.log('传入的class错误')
				return 0
			}
		} else {
			console.log('传入的class错误')
			return 0
		}
	}catch(err){
		console.log(err,'GetDomMaxHeighterr_')
	}
}
//我会在接口调用结束后已经拿到轮播图的数据且dom已经加载完成时对高度赋值

this.$nextTick(async ()=>{
				//如果轮播图加载成功 则动态获取轮播图高度
				if (this.bannerImags) {
					console.log(1,'1')
					let MaxHeight = await this.$tool.GetDomMaxHeight('get_image_height');
					console.log(MaxHeight,'最大高度');
					this.SwiperHeight = MaxHeight; 
                    
				}
			})

    SwiperHeight:默认值 0: 也可以给默认高度 后续会根据接口返回动态改变

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值