微信小程序开发笔记5—— IntersectionObserver应用之实现元素随着页面滚动吸附在顶部的效果

博客更新地址啦~,欢迎访问:https://jerryyuanj.github.io/

现在很多app都有这样的效果,某元素随着页面的滚动,吸附在顶部的效果。本文将介绍实现这种效果的两种不同的方法。
先看一下效果图:
sticky

使用IntersectionObserver

思路

上一篇博客详细介绍了IntersectionObserver的用法。这里用来实现这种吸附的效果,应该先想到的是,判断哪两个元素的相交。你可以根据需要来选择不同参照物。当相交的时候,将元素置顶吸附;不相交的时候,回到原来的位置。

实现
wxml

我将该页面分成了三部分。最上面是幻灯片,接着是的标签卡组件,最后是一个很长的内容区,因为要保证页面可以向下滚动的。

<view class="slider">
  <swiper class='slider-items' indicator-dots="{{true}}"
          indicator-color="white" interval="{{true}}">
    <block wx:for="{{[1,2,3]}}" wx:key="*this">
      <swiper-item>
        <view class='slider-item item-{{index}}'></view>
      </swiper-item>
    </block>
  </swiper>
</view>
<view class='{{tabFixed ? "fixed-tab" : ""}}'>
  <view class='tab'>
    <tabbar tabItems="{{tabOptions}}">
    </tabbar>
  </view>
</view>
<view class='content'></view>
wxss

这里要定义吸附的效果(fixed在顶部,即样式中的.fixed-tab)。

.slider{
  position: relative;
}
.slider-items{
  height: 260rpx;
}
.slider-item {
  width: 100%;
  height: 100%;
}
.item-0{
  background-color: lightblue;
}
.item-1{
  background-color: lightgreen;
}
.item-2{
  background-color: lightpink;
}
.tab{
  background-color: white;
}
.fixed-tab{
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 99;
}
.content{
  height: 1500px;
  background-color: #eaeaea;
  width: 100%;
}
js

initTabObserver方法中可以看到,使用的参照对象是页面,观察的是slider。当两者相交时(即slider在页面上能看到时),tab该在哪在哪;当不相交时(页面上看不到slider),就把tab置顶吸附。通过tabFixed来控制样式从而控制这种置顶吸附的效果。

Page({
  data: {
    tabFixed: false,
    tabOptions: ['全部', '附近', '特别关注']
  },
  /**
   * 初始化观察器
   */
  initTabObserver() {
    this.tabObserver = wx.createIntersectionObserver(this)
    this.tabObserver
      // 相对于页面可视区
      .relativeToViewport()
      // 相对于某一个元素
      .observe('.slider', (res) => {
        console.info(res)
        const visible = res.intersectionRatio > 0
        this.setData({ tabFixed: !visible })
      })
  },
  onLoad(){
    this.initTabObserver()
  },
  onUnload(){
    this.tabObserver.disconnect()
  }
})

我们也可以指定一个元素作为参照物,但是要注意,这个参照物,不能于我们的观察对象是相对静止的,即两者不以相同的速度相同的方向同时运动,否则永远也不会相交。我们可以对上面的代码做些改动:
在wxml中添加一个fixed的参照元素:

<view class='fixed-position'></view>

在wxss添加对应样式:

.fixed-position{
  width: 100%;
  height: 1px;
  position: fixed;
  visibility: hidden;
}

改写js中的initTabObserver方法:

initTabObserver() {
    this.tabObserver = wx.createIntersectionObserver(this)
    this.tabObserver
      .relativeTo('.fixed-position')
      .observe('.slider', (res) => {
        console.info(res)
        const visible = res.intersectionRatio > 0
        this.setData({ tabFixed: !visible })
      })
  },

一样可以达到同样的效果。

注意要在页面卸载的时候disconnect掉这个观察者,以免造成不必要的资源浪费。

使用onPageScroll

思路

这种方法就相对好理解一点了,也应该是常用的做法。就是在页面的滚动监听回调中,判断我们要吸附的元素距离顶部的距离x页面滚动距离y的大小。如果x > y,即还没有滚动到要吸附的元素的位置,保持原样;否则即切换样式,置顶吸附。

实现
wxml
<view class="placeholder-content flex-center">占位的一个div</view>
<view class='{{tabFixed ? "fixed-tab" : ""}}'>
  <view class='tab'>
    <tabbar tabItems="{{tabOptions}}">
    </tabbar>
  </view>
</view>
<view class='content'></view>
wxss
.container{
  height: 1000px;
  width: 100%;
}
.placeholder-content{
  height: 400rpx;
  width: 100%;
  background-color: green;
  color: white;
}
.tab{
  background-color: white;
}
.fixed-tab{
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 99;
}
.content{
  height: 800px;
  background-color: lightgray;
}
js

这种方法分两步:

  1. 获取tab最开始距离顶部的位置(或者tab上面元素的总高度,一个意思)。两种方式都可以,第二种在注释中。
  2. 页面滚动时,进行距离的判断
Page({
  data: {
    tabFixed: false,
    tabOptions: ['全部', '附近', '特别关注'],
    placeholderHeight: null
  },
  onPageScroll(e){
    // 页面滚动的距离
    const scrollDistance = e.scrollTop
    // 占位元素的高度
    const placeholderHeight = this.data.placeholderHeight
    this.setData({
      tabFixed: scrollDistance > placeholderHeight
    })
  },
  onReady(){
    const query = wx.createSelectorQuery()
    const self = this
    // 这里:获取placeholder的height = tab的top(顶部坐标)
    // 在你明确tab上面有A什么的时候,可以直接获取A的高度: example1
    // 否则,必须获取tab的top值: example2
    // example1
    query.select(".placeholder-content").boundingClientRect(function (res) {
      self.setData({
        placeholderHeight: res.height
      })
    }).exec()
    // example2
    /**
     * query.select(".tab").boundingClientRect(function (res) {
          console.info(res)
          self.setData({
            placeholderHeight: res.top
          })
        }).exec()
     */
  }
})

github

demo地址:https://github.com/JerryYuanJ/mini-app-pratice

  • 3
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 5
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值