本文已参与「新人创作礼」活动,一起开启掘金创作之路。
众所周知,可以滑动的 scroll 组件在移动端非常的重要,几乎每个页面都要用到。
一、布局分析,推导公式
二、计算变量的高度
2.1 计算单个节点高度
上面的公式中的变量有:页面可用高度, title 的高度,tab 的高度。
这里需要计算的就是 页面可用高度 和 title 的高度,因为为了简单 tab 的高度是写死的 50px, 当然不写死也没关系,在父组件中计算 tab 的高度传给子组件就好。
下面正式开始计算
//计算 scroll-view 的高度
computeScrollViewHeight() {
let that = this
let query = wx.createSelectorQuery().in(this)
query.select('.title').boundingClientRect(function(res) {
//得到标题的高度
let titleHeight = res.height
//scroll-view的高度 = 屏幕高度- tab高(50) - 10 - 10 - titleHeight
//获取屏幕可用高度
let screenHeight = wx.getSystemInfoSync().windowHeight
//计算 scroll-view 的高度
let scrollHeight = screenHeight - titleHeight - 70
that.setData({
scrollHeight: scrollHeight
})
}).exec()
},
这里主要是通过小程序封装的 API 来计算的。
wx.getSystemInfoSync() 可以得到设备的各种信息,关于高度的参数有两个,一个是屏幕高度 screenHeight,一个是可使用窗口高度 windowHeight。注意计算的时候要用 windowHeight,这样算出来的高度才是对的。screenHeight是手机的屏幕高度,包含了手机的状态栏和小程序标题栏。
有了可用屏幕高度,还需要元素的高度。计算元素高度小程序也提供了 API,参见 WXML节点信息API。
具体用法看文档就好了,精简的使用步骤就是:
let query = wx.createSelectorQuery().in(this)
query.select('.title').boundingClientRect(function(res) {
//在这里做计算,res里有需要的数据
}).exec()
注意在组件 component 里使用的话,要用 wx.createSelectorQuery().in(this) ,将选择器的选取范围更改为自定义组件component内。(初始时,选择器仅选取页面范围的节点,不会选取任何自定义组件中的节点。)
如果想同时测量多个节点的高度呢?
2.2 计算多个节点高度
能计算单个当然也能同时计算多个。如下:
computeScrollViewHeight() {
let that = this
let query = wx.createSelectorQuery().in(this)
query.select('.search').boundingClientRect()
query.select('.title-wrapper').boundingClientRect()
query.exec(res => {
let searchHeight = res[0].height
let titleHeight = res[1].height
let windowHeight = wx.getSystemInfoSync().windowHeight
let scrollHeight = windowHeight - searchHeight - titleHeight - 30 - 5 - 50
this.setData({ scrollHeight: scrollHeight})
})
},
有几个节点就写几个 query.select('.search').boundingClientRect(), 然后调用 query.exec() 执行操作获取节点信息的数组。
注意: 调用封装好的 computeScrollViewHeight() 的时机是在生命周期函数的 ready() 中,不能在 created(),否则取不到数据。
三、在 wxml 使用计算的结果 计算完成后如何使用呢?
<scroll-view scroll-y style='height: {{scrollHeight + "px"}}'></<scroll-view>
通过上面的方法使用。
注意:一定要在变量后面加上单位 px,不加的话会出错。
以上就是精确计算微信小程序scrollview高度的方法,从此再也不担心 scroll-view 高度错乱了!