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;
  });
},
相关推荐
遂心_6 分钟前
为什么 '1'.toString() 可以调用?深入理解 JavaScript 包装对象机制
前端·javascript
IT_陈寒7 分钟前
JavaScript 性能优化:5 个被低估的 V8 引擎技巧让你的代码快 200%
前端·人工智能·后端
王同学QaQ27 分钟前
Vue3对接UE,通过MQTT完成通讯
javascript·vue.js
岛风风28 分钟前
关于手机的设备信息
前端
ReturnTrue86841 分钟前
nginx性能优化之Gzip
前端
程序员鱼皮1 小时前
刚刚 Java 25 炸裂发布!让 Java 再次伟大
java·javascript·计算机·程序员·编程·开发·代码
w_y_fan1 小时前
Flutter 滚动组件总结
前端·flutter
wuli金居哇1 小时前
我用 Turborepo 搭了个 Monorepo 脚手架,开发体验直接起飞!
前端
Asort1 小时前
JavaScript 从零开始(五):运算符和表达式——从零开始掌握算术、比较与逻辑运算
前端·javascript
一枚前端小能手2 小时前
🚀 缓存用错了网站更慢?前端缓存策略的5个致命误区
前端·javascript