
注意:
1.小程序上下滑动页面,只通过当前划出顶部距离这一个值去判断选中状态,不要用元素离顶部的距离判断选中状态
2.点击导航栏不要切换选中样式,样式改变只能通过判断所在位置,否则会出现选中样式来回闪烁
3.获取元素顶部距离和高度是异步,需要隔一段时间再去获取,并且只需在onReady中获取一次
/**
* 生命周期函数--监听页面初次渲染完成
*/
onReady: function () {
var that=this;
setTimeout(function(){
var query=wx.createSelectorQuery();
query.select('.head').boundingClientRect();
query.select('.zhengce').boundingClientRect();
query.select('.tuwen').boundingClientRect();
// 获取每个元素顶部距离和高度
query.exec(function(res){
console.log(res)
that.setData({
query:res,
})
})
},500)
},
/**
* 页面滚动
*/
onPageScroll:function(e){
var that=this;
console.log(e.scrollTop)
console.log(that.data.query)
// 大于元素顶部距离,小于顶部距离+元素高度,60为导航栏高度
if(e.scrollTop>=0 && e.scrollTop<=that.data.query[0].height-60){
that.setData({
tab_dian:1,
})
}
if(e.scrollTop>=that.data.query[1].top-60 && e.scrollTop<=that.data.query[1].top+that.data.query[1].height-60){
that.setData({
tab_dian:2,
})
}
if(e.scrollTop>=that.data.query[2].top-60 && e.scrollTop<=that.data.query[2].top+that.data.query[2].height-60){
that.setData({
tab_dian:3,
})
}
},
来源:https://www.cnblogs.com/haoming159/p/13019609.html