小程序:页面滚动到某个位置导航条固定效果

代码

<!--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;
在这里插入图片描述

效果

在这里插入图片描述
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_43972437/article/details/125835948