uni-app 中 swiper 轮播图高度自适应

方法一

1、首先 swiper 标签的宽度是 width: 100%

2、swiper 标签存在默认高度是 height: 150px ;高度无法实现由内容撑开,在默认情况下,图片的高度显示总是 150px

swiper 宽度 / swiper 高度 = 原图宽度 / 原图高度

swiper 高度 = swiper 宽度 * 原图高度 / 原图宽度

html 复制代码
<swiper class="swiper-box" indicator-dots autoplay circular>
  <swiper-item v-for="(item, i) in imgList" :key="i">
    <image style="width: 100%" :src="item" mode="widthFix" />
  </swiper-item>
</swiper>
css 复制代码
.swiper-box {
  width: 100%;
  height: calc(100vw * 9 / 16);
}

方法二

1、在每次滑动切换的时候,动态地获取 swiper-item 内部的 DOM 的元素的高度

2、将获取的高度动态设置给 swiper 元素

html 复制代码
<swiper
  :current="currIndex"
  @change="changeSwiper"
  :style="{ height: swiperHeight + 'px' }"
  indicator-dots
  autoplay
  circular
  :duration="1000"
>
  <swiper-item v-for="(item, i) in imgList" :key="i">
    <image :id="'wrap' + i" style="width: 100%" :src="item" mode="widthFix" />
  </swiper-item>
</swiper>
javascript 复制代码
currIndex: 0, // 当前索引
swiperHeight: 0, // 滑块的高度(单位px)
javascript 复制代码
onLoad(e) {
  this.$nextTick(() => {
    this.setSwiperHeight(); // 动态设置 swiper 的高度
  });
},
javascript 复制代码
/* 切换 swiper 滑块 */
changeSwiper(e) {
  this.currIndex = e.detail.current;
  this.$nextTick(() => {
    this.setSwiperHeight(); // 动态设置 swiper 的高度
  });
},
/* 动态设置 swiper 的高度 */
setSwiperHeight() {
  const element = "#wrap" + this.currIndex;
  const query = uni.createSelectorQuery().in(this);
  query.select(element).boundingClientRect();
  query.exec(res => {
    if (res && res[0]) this.swiperHeight = res[0].height;
  });
},
相关推荐
ricardo197313 小时前
手写一个虚拟列表,万级数据滚动 FPS 稳定 60 帧
前端
小KK_13 小时前
新手必看:一篇文章带你搞懂JavaScript作用域
前端
万邦科技Lafite13 小时前
如何通过 item_search_img API 接口获取淘宝商品信息
java·前端·数据库
Jx65714 小时前
初学者视角下的JavaScript作用域理解
javascript
AlbertZein14 小时前
干了三年全栈才悟到:TS + React 这套组合,真不是堆技术堆出来的
前端
化为五月14 小时前
我把 Hermes 接进了飞书,结果卡在“能发消息但就是不回”
前端
ClouGence14 小时前
豆包收费之后,我找到了更好用的 AI 工具
前端·人工智能·后端·ai·ai编程·ai写作
aircrushin14 小时前
音乐节结束前,拿手机📱搓了一个工具
前端·后端
廖松洋(Alina)14 小时前
07答案比对与反馈UI-鸿蒙PC端Electron开发
javascript·ui·华为·electron·开源·harmonyos·鸿蒙
风骏时光牛马14 小时前
Cube Sandbox部署问题及解决方法
前端