小程序-元素滚动吸附至顶部

274 阅读1分钟
  • text.wxml
<view class="top"></view>
<view class="fix-container">
  <view class="fix-content {{fixed ? 'fixed' : ''}}">fix content</view>
</view>
<view class="bottom"></view>

-test.wxss

.top{
  height: 598px;
  background-color: #fff;
}
.fix-container{
  height: 60px;
  background-color: #458445;
}
.fix-content{
  width: 100%;
  height: 60px;
  background-color: #458445;
}
.bottom{
  height: 800px;
  background:#fff;
}
.fixed{
  position: fixed;
  top: 0;
}

-test.js

Page({
  data: {
    fixed: false
  },
  onLoad: function () {
    let observer = wx.createIntersectionObserver(this)
    observer.relativeToViewport({ top: - 60 }).observe(".fix-container", res => {
      console.log("触发", res);
      if (res.intersectionRatio == 0) {
        this.setData({ fixed: true })
      } else {
        this.setData({ fixed: false })
      }
    })
  },
})
  • 注意点: relativeToViewport中top值为吸附元素的高度的负值(暂不知为何),吸附元素不可超出可视区范围,否则会出现滚动条滚回顶部,元素依然吸附