微信小程序(滚动吸顶)

1、sticky/index.wxml




  
    {{item}}
  


  
    {{index+1}} 
  

2、sticky/index.js

// pages/wxCase/sticky/index.js
Page({
  data: {
    navList: ['正在进行', '即将开始', '已结束'],
    nav_type: 0,//默认选中第一个数据
    isFixed: false,//是否吸顶
    navTop: 0,//nav菜单距离顶部距离
  },
  changeType(e) {
    let { index } = e.currentTarget.dataset;
    if (this.data.nav_type == index || index == undefined) return;
    this.setData({
      nav_type: index
    })
    if (this.data.isFixed) {
      wx.pageScrollTo({
        selector: '#content',
        duration: 0.5//滚动动指定位置需要时间
      })
    }
  },
  onReady() {
    // 获取节点距离顶部的距离
    wx.createSelectorQuery().select("#nav").boundingClientRect((rect) => {
      if (rect && rect.top) {
        this.setData({
          navTop: parseInt(rect.top)
        })
      }
    }).exec()
  },
  // 监听页面滚动事件
  onPageScroll(e) {
    let scrollTop = parseInt(e.scrollTop),
      isFixed = scrollTop >= this.data.navTop;
    if (this.data.isFixed !== isFixed) {
      this.setData({
        isFixed
      })
    }
  }
})

3、sticky/index.wxss

.head-title {
  background: linear-gradient(to right, #ef629f, #eecda3);
  height: 300rpx;
  width: 100%;
  box-sizing: border-box;
  padding: 20rpx;
  font-size: 25rpx;
  color: #fff;
}

.hd {
  width: 100%;
  height: 88rpx;
  line-height: 88rpx;
  display: flex;
  background: #fff;
  box-shadow: 0 5rpx 5rpx #ccc;
  position: relative;
}

.hd-item {
  flex: 1;
  text-align: center;
  font-weight: 500;
  color: #333;
  font-size: 28rpx;
  position: relative;
}

.hd-item::after {
  content: '';
  position: absolute;
  /* 设置默认宽度为0 */
  width: 0%;
  height: 6rpx;
  background: linear-gradient(to right, #ef629f, #eecda3);
  border-radius: 3rpx;
  left: 50%;
  transform: translate(-50%);
  bottom: 4rpx;
  /* 添加过渡效果 */
  transition: 0.3s width linear;
}

/* 激活选中样式 */
.hd-item.active {
  font-size: 30rpx;
  background-clip: text;
  -webkit-background-clip: text;
  color: transparent;
  background-image: linear-gradient(to right, #ef629f, #eecda3);
  transition: 0.3s all linear;
  transition-delay: 0.1s;
}

.hd-item.active::after {
  width: 40%;
}

.content view {
  background: #fff;
  height: 50rpx;
  line-height: 50rpx;
  border-bottom: 1rpx solid #eaeef1;
  padding: 20rpx;
  color: #999;
  text-align: center;
}

.content.pt {
  padding-top: 88rpx;
  /* nav的高度 */
}

.fixed {
  position: fixed;
  left: 0;
  top: 0;
  z-index: 1;
}

4、sticky/index.json

{
  "usingComponents": {},
  "navigationBarTitleText": "滚动吸顶"
}

微信小程序(滚动吸顶)_第1张图片

 

你可能感兴趣的:(微信小程序,小程序)