问题
scroll-view要求必须要定高度,但是手机尺寸不同需要自适应
思路:
scroll-view组件高度
= 手机屏幕可用高度 -当前页面其他元素高度
手机屏幕可用高度通过小程序封装的 APIwx.getSystemInfoSync()
去获取 api传送带
注意screenHeight
是手机的屏幕高度,包含了手机的状态栏和小程序标题栏,windowHeight
才是需要的可用高度
基础代码实现
let query = wx.createSelectorQuery().in(this)
query.select('.box').boundingClientRect(function(res) {
//在这里做计算,res里有需要的数据
}).exec()
实例 - 计算多个节点高度
/**
* 生命周期函数--监听页面初次渲染完成
*/
onReady: function () {
this.computeScrollViewHeight()
},
//计算 scroll-view 的高度,组件属性的长度单位默认为px
computeScrollViewHeight() {
//获取手机屏幕可用高度
let screenHeight = wx.getSystemInfoSync().windowHeight
// 通过query 获取其余盒子的高度
let query = wx.createSelectorQuery().in(this)
query.select('.header-box').boundingClientRect()
query.select('.selectBoxAll').boundingClientRect()
query.exec(res => {
let headHeight = res[0].height
let selectBoxHeight = res[1].height
//scroll-view的高度 = 屏幕高度 - 搜索框 - 下拉搜索
let scrollHeight = screenHeight - headHeight - selectBoxHeight
this.setData({
screenHeight: screenHeight,
scrollHeight: scrollHeight
})
})
},
<!-- 滚动区域-->
<scroll-view scroll-y="true" style='height: {{scrollHeight + "px"}}' scroll-into-view="{{jumpPoint}}">
</scroll-view>
注: 调用封装好的 computeScrollViewHeight() 的时机是在生命周期函数的 ready() 中,不能在
created(),否则取不到数据。