当前位置:   article > 正文

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

uniapp swiper自适应高度

方法一(好像只对第一张起作用)

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

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

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

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

  1. <swiper class="swiper-box" indicator-dots autoplay circular>
  2. <swiper-item v-for="(item, i) in imgList" :key="i">
  3. <image style="width: 100%" :src="item" mode="widthFix" />
  4. </swiper-item>
  5. </swiper>
  1. .swiper-box {
  2. width: 100%;
  3. height: calc(100vw * 9 / 16);
  4. }

方法二(推荐)

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

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

  1. <swiper
  2. :current="currIndex"
  3. @change="changeSwiper"
  4. :style="{ height: swiperHeight + 'px' }"
  5. indicator-dots
  6. autoplay
  7. circular
  8. :duration="1000"
  9. >
  10. <swiper-item v-for="(item, i) in imgList" :key="i">
  11. <image :id="'wrap' + i" style="width: 100%" :src="item" mode="widthFix" />
  12. </swiper-item>
  13. </swiper>
  1. currIndex: 0, // 当前索引
  2. swiperHeight: 0, // 滑块的高度(单位px)
  1. onLoad(e) {
  2. this.$nextTick(() => {
  3. this.setSwiperHeight(); // 动态设置 swiper 的高度
  4. });
  5. },
  1. /* 切换 swiper 滑块 */
  2. changeSwiper(e) {
  3. this.currIndex = e.detail.current;
  4. this.$nextTick(() => {
  5. this.setSwiperHeight(); // 动态设置 swiper 的高度
  6. });
  7. },
  8. /* 动态设置 swiper 的高度 */
  9. setSwiperHeight() {
  10. const element = "#wrap" + this.currIndex;
  11. const query = uni.createSelectorQuery().in(this);
  12. query.select(element).boundingClientRect();
  13. query.exec(res => {
  14. if (res && res[0]) this.swiperHeight = res[0].height;
  15. });
  16. },
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/天景科技苑/article/detail/954090
推荐阅读
相关标签
  

闽ICP备14008679号