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;
  });
},
相关推荐
万少4 小时前
HarmonyOS 开发必会 5 种 Builder 详解
前端·harmonyos
橙序员小站6 小时前
Agent Skill 是什么?一文讲透 Agent Skill 的设计与实现
前端·后端
炫饭第一名9 小时前
速通Canvas指北🦮——基础入门篇
前端·javascript·程序员
王晓枫9 小时前
flutter接入三方库运行报错:Error running pod install
前端·flutter
符方昊9 小时前
React 19 对比 React 16 新特性解析
前端·react.js
ssshooter9 小时前
又被 Safari 差异坑了:textContent 拿到的值居然没换行?
前端
曲折9 小时前
Cesium-气象要素PNG色斑图叠加
前端·cesium
Forever7_9 小时前
Electron 淘汰!新的桌面端框架 更强大、更轻量化
前端·vue.js
Angelial9 小时前
Vue3 嵌套路由 KeepAlive:动态缓存与反向配置方案
前端·vue.js
jiayu10 小时前
Angular学习笔记24:Angular 响应式表单 FormArray 与 FormGroup 相互嵌套
前端