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;
  });
},
相关推荐
AlienZHOU7 小时前
AI Coding 时代下,我的技术面试实践分享
前端·后端·面试
Captaincc10 小时前
AI用量v0.1.11更新发布 新增 jusage doctor 诊断指令 托盘展示token 和余额 新增 AutoClaw 支持
前端·后端·vibecoding
计算机魔术师11 小时前
德国Wiki被黑后两周,OpenAI终于把模型失控的账本摊开了
前端
kyriewen12 小时前
我让 AI 当面试官面了我一轮:第 3 个追问我就卡住了(附 10 道追问清单)
前端·面试·ai编程
IT_陈寒12 小时前
Python的GIL把我坑惨了,多线程跑得比单线程还慢
前端·人工智能·后端
前端snow12 小时前
ai agent --- 多agent框架之图编排引擎-langgraph
前端
竹林81813 小时前
OmniPic Studio v3.2.1 核心技术架构与全平台发版解析文档
前端·浏览器
JamesZhang8007813 小时前
页面内存只涨不跌? 一次泄漏排查, 牵出 WeakMap 的诞生
前端
Z小明13 小时前
第 6 章 组件进阶
前端·vue.js
江华森13 小时前
HTTP请求的完整过程详解:从DNS解析到TCP挥手的微秒级实战分析
前端