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;
  });
},
相关推荐
vim怎么退出16 小时前
Dive into React——Diff 算法
前端·react.js·源码阅读
半个落月16 小时前
面试必问的 JS 原型链,我用 16 个示例给你彻底讲明白
javascript
拾年27516 小时前
别调 BERT 了:我用 Prompt 做了套 NLP 系统,20 分钟搞定
前端·人工智能
丷丩16 小时前
12. 渲染:MapLibre GL JS 集成与多源瓦片联动
javascript·矢量瓦片·maplibre gl js·地图服务器
半个落月16 小时前
别再死记变量提升了——从 V8 编译过程真正理解 JS 执行机制
前端
橘子星17 小时前
别再懵圈!JS 执行机制的 “千层套路” 全揭秘
前端·javascript
GuWenyue17 小时前
LeetCode 76 最小覆盖子串|JS 滑动窗口标准解法
前端·算法·面试
YHHLAI17 小时前
前端 HTTP 请求 & LLM 接口开发
前端·网络协议·http
拾年27517 小时前
__proto__ vs prototype:90% 的人分不清的 JavaScript 核心
前端·javascript·面试
国科安芯17 小时前
国科安芯推出商业航天级抗辐照半双工 RS485 收发器 ASC485S2Y
前端·单片机·嵌入式硬件·架构·安全性测试