小程序swiper限高高度自适应解决方案

2018-12-12  本文已影响0人  C_razy
方案一:满屏
QQ截图20181212112423.png
/*wxml*/
 <swiper style='width:100%;height:100%;' current='{{current}}' bindchange='bindChange'>

切记是行内样式

/*wxss*/
swiper-item {
  overflow: scroll;
}

ok完美解决!

方案二:半屏

这个才是重点,小二,上酸菜!!


QQ截图20181212113929.png

这个就不能行内设置height:100%;了,要根据元素节点动态设置高,红框中的是我的循环元素,要获得每个swiper-item的高

//js
get_wxml: function (className, callback){
    wx.createSelectorQuery().selectAll(className).boundingClientRect(callback).exec()
  },
wx.request({
      url: baseUrl + 'm=wttapi&a=getcategories',
      method: "POST",
      header: {
        "Content-Type": "application/x-www-form-urlencoded"
      },
      success: function(res) {
        console.log(res)
        that.setData({
          scrollNav: res.data.data[1],
          scrollContent: res.data.data[2],
          indexTit: res.data.data[1][0].name
        })
        let change_id = that.data.scrollNav[that.data.idx].cid//动态获取每个swiper-item元素节点的id
        that.setData({
          swiper_length: that.data.scrollNav.length-1//获取节点数量
        })
        //获取节点信息
        that.get_wxml(`#cont${change_id}`,(rects)=>{
          that.setData({
            height:rects[0].height
          })
        })
      }
    })
/*wxml*/
<swiper style='width:100%;height:{{height}}px;background:#F5F5F5;' current='{{current}}' bindchange='moveSwiper'>
    <swiper-item wx:for='{{scrollNav}}' wx:for-item='item' wx:key='index' class='swiper_content' item-id='{{item.cid}}'>
      <!-- <view class='loading'>
        <image src='/images/loading.gif'></image>
        <text>努力加载中</text>
      </view> -->
      <view id='cont{{item.cid}}'>
        <view wx:for='{{scrollContent}}' wx:key='index' id='cont{{item[0].pcid}}'>
          <view class='content-title'>
            <image src='/images/lefticon@2x.png'></image>
            <text style='display:inline-block;margin:0 10rpx;'>{{item[0].pcname}}</text>
            <image src='/images/righticon@2x.png'></image>
          </view>
          <view class='content-box'>
            <view wx:for='{{scrollContent[index]}}' wx:key='index' class='content-box-list' data-id='{{item.ccid}}' data-name='{{item.name}}' bindtap='intoList'>
              <image src='{{item.image}}' style='max-width:160rpx;max-height:160rpx;'></image>
              <view class='content-box-price'>
                <view>
                  <text class='price-text1 fontweight'>{{item.name}}</text>
                  <text class='price-text2'>今日最值</text>
                </view>
                <text class='price-text3'>{{item.price}}</text>
              </view>
            </view>
          </view>
        </view>
      </view>
    </swiper-item>
  </swiper>

ok,小白一枚,以上两种方案是小程序初步踩坑经验

上一篇下一篇

猜你喜欢

热点阅读