小城序swiper高度设置动态跟随图片高度

场景,一个页面里面多个轮播,且图片数据由后台控制
自己定义组件mySwiper

<!--components/mySwiper/mySwiper.wxml-->
        <swiper class="swiper" style="height: {{maxH}}px;" autoplay="{{autoplay}}" indicatorDots="{{indicatorDots}}" interval="2000" duration="500" indicator-color="#C9DCF9"	indicator-active-color="#99B7E8" circular>
          <block wx:for="{{list}}" wx:key="index">
            <swiper-item class="swiper-item">
                <image class="radiusMed" style="width: {{boxW}}px;" data-item="{{item}}"  src="{{item.url}}" mode="widthFix" bindload="bindloadHandle"></image>
            </swiper-item>
          </block>
        </swiper>

mySwiper.js

 properties: {
    pId:{
      type:String
    },
    list:{
      type:Array
    },
    autoplay:{
      type:Boolean,
      data:false
    },
    indicatorDots:{
      type:Boolean,
      data:false
    }
  },
  data: {
    boxW:100,
    maxH:50
  },
...
// 图片加载触发
 bindloadHandle({detail}) {
 	// 由于盒子外部有边距,所以计算的时候不能拿屏幕的宽,应该拿父盒子的
      const query=wx.createSelectorQuery()
      query.select('#'+this.properties.pId).boundingClientRect()
      query.exec(res=>{
        const boxW=res[0].width
         // 计算比值
        const ratio = detail.width / detail.height;
        // 得出实际高度
        const imgH=parseInt(boxW / ratio);
        if(imgH>this.data.maxH) this.data.maxH=imgH
        this.setData({
          boxW,
          maxH:this.data.maxH
        })
      })
...

调用

 <view id="topBannerSwiper">
      <mySwiper autoplay indicatorDots  list="{{sys_home_banner}}" pId="topBannerSwiper" />
    </view>
在小程中,实现 swiper 组件高度跟随图片高度可采用以下方法: ### 动态计算高度法 由于小程swiper 标签有固定高度 150px,而实际希望轮播图高度动态改变,可通过 js 动态计算图片高度设置swiper 组件。例如在获取图片信息后,将高度动态赋值给 swiper。不过在实现时,存在将获取到的高度传递给组件的问题,组件中有 swiperClass 属性可传递高度,但在 css 中写从 js 中获取的值可能存在困难,也可考虑给组件添加一个高度属性来解决高度传递问题 [^1][^2]。 ### 利用 swiper + scroll - view 及 CSS 布局法 这是一种新的思路,使用 swiper + scroll - view,在 css 中使用 display: flex,父元素设置 flex: 1。此方法可应对 swiper 的子元素高度不固定的情况,避免常规用 js 动态高度的方式 [^3]。 以下是一个简单示例代码,展示动态计算高度法: ```javascript // pages/index/index.js Page({ data: { swiperHeight: 0, images: [ 'https://example.com/image1.jpg', 'https://example.com/image2.jpg', 'https://example.com/image3.jpg' ] }, onLoad() { const query = wx.createSelectorQuery(); query.select('.swiper-image').boundingClientRect(rect => { this.setData({ swiperHeight: rect.height }); }).exec(); } }) ``` ```xml <!-- pages/index/index.wxml --> <swiper style="height: {{swiperHeight}}px"> <block wx:for="{{images}}" wx:key="*this"> <swiper-item> <image class="swiper-image" src="{{item}}" mode="widthFix"></image> </swiper-item> </block> </swiper> ```
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值