页面的布局是这样子的
需求是选项一、二、三、四要能吸顶,如果不是放在scroll-view中,可用 css position:fixed; 来实现,但现在是想在scroll-view中实现这个效果,经过一番折腾,终于另辟蹊径找到了一条不一样的路子。
整体布局没做多大改动,只是将下半部份的主体内容,放到了一个scroll-view里面,然后内部的子scroll-view滚动时,判断一下导航条距离顶部的位置,如果大于0,则重置子scroll-view的scroll-top为0。
<!--index.wxml-->
<view class="container">
<view class="main">
<scroll-view scroll-y="{{true}}" style="height:{{scrollViewHeight}}px;">
<view class="block">asdfasdfasdf</view>
<view class="block">asdfasdfasdf</view>
<view class="nav" id="nav">
<view class="item item-hover">选项一</view>
<view class="item">选项二</view>
<view class="item">选项三</view>
<view class="item">选项四</view>
</view>
<scroll-view scroll-y="{{true}}" scroll-top="{{subScrollTop}}" style="height:{{subScrollViewHeight}}px;" scroll-with-animation="true" bindscroll="scrollChange">
<view class="block">asdfasdfasdf</view>
<view class="block">asdfasdfasdf</view>
<view class="block">asdfasdfasdf</view>
<view class="block">asdfasdfasdf</view>
<view class="block">asdfasdfasdf</view>
<view class="block">asdfasdfasdf</view>
</scroll-view>
</scroll-view>
</view>
<view class="footer" id="footer">
<button>按钮一</button>
<button>按钮二</button>
<button>按钮三</button>
</view>
</view>
// index.js
Page({
data:{
scrollViewHeight: 0,
windowHeight: 0,
footerViewHeight: 0,
subScrollViewHeight: 0,
subScrollTop: 0,
},
onReady: function(e){
var that = this;
wx.getSystemInfo({
success: function (res) {
that.setData({
windowHeight: res.windowHeight,
});
//计算主scroll-view和footer页脚高度
wx.createSelectorQuery().select('#footer').boundingClientRect( (res) => {
var footerViewHeight = res.height;
var scrollViewHeight = that.data.windowHeight - footerViewHeight;
that.setData({
scrollViewHeight: scrollViewHeight,
footerViewHeight: footerViewHeight
});
}).exec();
//计算子scroll-view组件高度
wx.createSelectorQuery().select('#nav').boundingClientRect( (res) => {
if(res && parseInt(res.height)>0){
that.setData({
subScrollViewHeight: that.data.scrollViewHeight - res.height
});
}
}).exec();
}
});
},
scrollChange: function(e){
var that = this;
//当子scroll-view向上滚动的时候,判断nav导航条距离顶部的距离,如果大于0,则还没到顶部,此时使用scroll-top属性,将子scroll-view的滚动条重置到0
wx.createSelectorQuery().select('#nav').boundingClientRect( (res) => {
if(e.detail.deltaY<0){
// console.log('向上滚动')
if(res.top>0){
that.setData({
subScrollTop:0
});
}
}
}).exec();
},
})
/**index.wxss**/
page{
height: 100%;
}
.container{
width: 750rpx;
height: 100%;
margin: 0;
padding: 0;
display: flex;
flex-direction: column;
justify-content: space-between;
}
.main{
width: 750rpx;
flex: 1;
}
.nav{
height: 150rpx;
background-color:blue;
color:#fff;
display: flex;
flex-direction: row;
justify-content: space-between;
align-items: center;
}
.block{
height: 300rpx;
background-color: #f00;
margin: 10rpx 0;
}
.footer{
width: 750rpx;
height: 150rpx;
background-color: #ccc;
display: flex;
flex-direction: row;
align-items: center;
}
.footer button{
width: 200rpx;
height: 50rpx;
font-size: 26rpx;
display: flex;
align-items: center;
}
效果如下: