function getScrollViewHeight(needSubDoms) {
let that = this;
// 第一步获取设备高度
wx.getSystemInfo({
success: function (res) {
that.setData({
windowHeight: res.windowHeight
});
}
});
// 第二步 然后取出 传入的doms 的高度
// 根据文档,先创建一个SelectorQuery对象实例
let query = wx.createSelectorQuery().in(that);
// 然后逐个取出节点信息
needSubDoms.forEach(dom => {
query.select(dom).boundingClientRect();
})
// 执行上面所指定的请求,结果会按照顺序存放于一个数组中,在callback的第一个参数中返回
query.exec((res) => {
// 批量计算 需要减去的dom 的高度
let reduceHeight = res.reduce((prev, current) => prev + current.height, 0);
// 然后就是做个减法
let scrollViewHeight = that.data.windowHeight - reduceHeight - 10;
// 算出来之后存到data对象里面
that.setData({
scrollViewHeight: scrollViewHeight
});
});
}
然后在需要自适应scroll-view高度的页面中的onReady中调用方法
onReady() {
// 在没有tabBar的页面中,需要在onReady中获取高度,才能准确的获取到准确的高度,在页面渲染之前获取的高度是减去tabBar之后的高度
utilLib.getScrollViewHeight.bind(this)(['.search_box', '.bottom_content']);
},
<scroll-view scroll-y="true" style="height: {{ scrollViewHeight }}px">
...
</scroll-view>