小程序中使用swiper轮播自定义高度

小程序中使用swiper轮播图时默认高度为150px。

设置自定义高度时我们需要盒子的高度随着内容的增加而增加所以高度就不能写死 我试了将外层的盒子高度设置为100%但是好像没有生效 swiper会默认将多余150px的内容的截去掉。

所以写了一个监控内容高度设置swiper盒子的高度的方法提供参考

<view class="tuijian_box pl30 pr30">
 <view class="tuijian_tit c-tuijian_tit">今日推荐</view>
 <swiper current="{{currentTab}}" duration="1000" bindchange="swiperTabView" bindchange="changeswiper"       style="height:{{height}}" >        
<swiper-item>
     <view class="list">
     <view class="fl c-tuijian_item" wx:if="{{recommendList}}" wx:for="{{recommendList}}" wx:key="{{index}}">               
             <image src="{{item.imgBase64}}"></image>
             <view class="shadow">1{{item.mnm}}</view>  </view>   
      <view style="clear: both;"></view>
 </view>      
  </swiper-item>      
  <swiper-item>
     <view class="list">
         <view class="fl c-tuijian_item" wx:if="{{recommendList}}" wx:for="{{recommendList}}" wx:key="{{index}}">               
             <image src="{{item.imgBase64}}"></image>
             <view class="shadow">2{{item.mnm}}</view>
         </view>   
     <view style="clear: both;"></view>
   </view>      
</swiper-item>   
 <swiper-item>
 <view class="list">
         <view class="fl c-tuijian_item" wx:if="{{recommendList}}" wx:for="{{recommendList}}" wx:key="{{index}}">                 
                <image src="{{item.imgBase64}}"></image>
                <view class="shadow">2{{item.mnm}}</view>
         </view>   
         <view style="clear: both;"></view>
 </view>        
</swiper-item>   
 </swiper>
 </view>

js的部分

Page({ 
    data:{
        currentTab: 0, //滑动切换数据 
        height:'', //设置滑动切换的swiper高度
        heights:[] 
    },
 onLoad: function () {
 var _this = this;
 setTimeout(function () {//异步 //设置滑动切换今日推荐的高度
     var query = wx.createSelectorQuery();
     query.selectAll('.list').boundingClientRect()
     query.exec((res) => {
             var listHeight = res[0][0].height
             _this.setData({
                     heights: res[0],
                     height: listHeight + 'px'
                 })
             })
            }, 800)
 },
changeswiper:function(e){ //设置滑动切换今日推荐的高度
   console.log(e.detail.current)
     var _this = this;
     setTimeout(function () {//异步
     var query = wx.createSelectorQuery();//模仿dom获取组件的高度
     query.selectAll('.list').boundingClientRect()
     query.exec((res) => {
         var listHeight = res[0][e.detail.current].height
         console.log(res[0][e.detail.current].height)
         _this.setData({height: listHeight + 20 + 'px' })
         }) 
      }, 800)
 },
 //滑动切换
 swiperTabView: function (e) {
         this.setData({
                 currentTab: e.detail.current
             });
 },
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容