微信小程序swiper控件高度自适应

在小程序开发文档中,swiper控件默认高度为150,高度必须设置具体的值,所以为了适应不同分辨率的设备,通过动态的获取屏幕空白部分高度在设置swiper控件的高度

主要用到两个API:

1、getSystemInfo(获取当前设备的屏幕信息)

2、createSelectorQuery(这里的作用是获取其他控件的高度)

在wxml文件中用一个view控件将表头包裹起来,然后设置class为all_view

在js中的data中添加两个字段

    // 页面总高度将会放在这里
    windowHeight: 0,
    // scroll-view的高度
    swiperViewHeight: 0

在js中新建一个方法:setSwiperHeight,用来动态设置swiper控件的高度

setSwiperHeight: function () {
    let that = this

    wx.getSystemInfo({
      success: function(res) {
        that.setData({
          windowHeight: res.windowHeight,
        });
      }
    });
    // 根据文档中的介绍,先创建一个SelectorQuery对象实例
    let query = wx.createSelectorQuery().in(this);

    query.select('.all_view').boundingClientRect();

    // 执行上面所指定的请求,结果会按照顺序存放于一个数组中,在callback的第一个参数中返回
    query.exec((res) => {
      //取出表头高度
      let headerHeight = res[0].height;
      // 计算出去除表头剩余的高度
      let swiperViewHeight = this.data.windowHeight - headerHeight;

      this.setData({
        swiperViewHeight: swiperViewHeight
      });
    });

  },

然后在wxml中将数据与控件绑定即可

    <swiper current="{{TabCur}}" duration="300" easing-function="easeOutCubic" style="height:{{swiperViewHeight}}px">
        <swiper-item>
            <view class="swiper_item_0">
            testestsetsetsetsettsette
        </view>

        </swiper-item>
        <swiper-item><view>test</view></swiper-item>
    </swiper>

完成后效果如下

发布了181 篇原创文章 · 获赞 68 · 访问量 9万+

猜你喜欢

转载自blog.csdn.net/wx_lanyu/article/details/99054600