代码
<!--index.wxml-->
<scroll-view scroll-y class="container" bindscroll="scroll">
<view class="nav-top {
{ scrollTop > 300 ? 'fix-top' : '' }}">
顶部导航{
{
scrollTop }}
</view>
<view wx:for="{
{ 120 }}" wx:key="item">{
{
item }}</view>
</scroll-view>
// index.js
Page({
data: {
scrollTop: 0
},
scroll(e) {
console.log(e)
const scrollTop = e.detail.scrollTop
this.setData({
scrollTop})
},
})
这里打印出的 e 是:
/**index.wxss**/
.container {
// 切记这个必须要加
height: 100vh;
}
.nav-top {
width: 100%;
height: 100rpx;
background-color: #f00;
}
.fix-top {
position: fixed;
top: 0;
background-color: #ff0;
}
注意的点
我们设置了 container 的样式为 height: 100vh;
效果