在移动端,页面过长时,为了提高用户体验,会使用吸顶将重要信息固定于顶部,所以封装了一个吸顶组件,方便以后使用
可以扫码查看是否符合自己的需求
<view class="sticky-container" style="height: {{ containerInfo.top <= top ? (containerHeight + 'px') : 'auto' }}">
<view class="sticky-position {{ containerInfo.top <= top ? 'position-fixed' : '' }}" style="width: {{ containerInfo.width }}px; left: {{ containerInfo.left }}px; top: {{ top }}px;">
<slot>slot>
view>
view>
// components/stickyTop/index.js
Component({
/**
* 组件的属性列表
*/
properties: {
scrollTop: {
type: Number,
value: 0,
observer(newData, oldData) {
this.getStickyOffsetTop()
}
},
top: {
type: Number,
value: 0
}
},
/**
* 组件的初始数据
*/
data: {
containerHeight: '',
containerInfo: {}
},
/**
* 组件的方法列表
*/
methods: {
// 获取当前容器的offsetTop
getStickyOffsetTop() {
wx.createSelectorQuery().in(this).select('.sticky-container').boundingClientRect(res => {
// console.log(res);
if (res.top < this.properties.top) {
this.setData({
containerHeight: res.height
})
}
this.setData({
containerInfo: res
})
}).exec()
}
}
})
/* components/stickyTop/index.wxss */
.position-fixed{
position: fixed;
top: 0;
}
"usingComponents": {
"sticky-top": "../../components/stickyTop"
}
<view class="container">
<view class="green-block">view>
<view class="green-block">view>
<sticky-top scrollTop="{{ scrollTop }}" top="0">
<view class="red-block">吸顶view>
sticky-top>
<view class="yellow-block">view>
<view class="green-block">view>
<sticky-top scrollTop="{{ scrollTop }}" top="200">
<view class="yellow-block">吸顶-距顶部200的距离view>
sticky-top>
<view class="green-block">view>
<view class="green-block">view>
<view class="green-block">view>
<view class="green-block">view>
<view class="green-block">view>
<view class="green-block">view>
<view class="green-block">view>
<view class="green-block">view>
<view class="green-block">view>
<view class="green-block">view>
view>
/**
* 监听页面滚动事件
*/
onPageScroll(e) {
this.setData({
scrollTop: e.scrollTop
})
},
/* pages/useStickyTop/index.wxss */
.green-block{
height: 200rpx;
margin: 40rpx;
background-color: var(--primary);
}
.red-block{
margin: 0 40rpx;
height: 200rpx;
line-height: 200rpx;
background-color: rgb(236, 83, 48);
text-align: center;
color: #ffffff;
}
.yellow-block{
margin: 0 40rpx;
height: 100rpx;
line-height: 100rpx;
background-color: rgb(199, 186, 6);
text-align: center;
color: #ffffff;
}