美文网首页
微信小程序 wepy中 affix 图钉 吸顶效果实现

微信小程序 wepy中 affix 图钉 吸顶效果实现

作者: harryfun | 来源:发表于2019-06-24 14:20 被阅读0次

    1. 思路

    实现这个效果的思路并不难,主要分为两个部分

    • 动态的获取要设置图钉元素距离顶部的距离
    • 监听页面滚动事件,当页面滚动的距离大于等于图钉元素距离顶部的距离时,给设置图钉的元素加上一个固定定位。

    2. 动态获取距离

    我们都知道,微信小程序和vue类似,一般情况下是不需要直接获取dom元素的,都是用数据控制视图。但是当前这个需求,我们需要获取到这个dom元素,并且找到他的scrollTop这样一个值,那么,经过阅读了微信小程序的文档之后,我们发现,SelectorQuery wx.createSelectorQuery()这样一个api,可以返回一个 SelectorQuery 对象实例。
    示例代码:

    const query = wx.createSelectorQuery()
    query.select('#the-id').boundingClientRect()
    query.selectViewport().scrollOffset()
    query.exec(function(res){
      res[0].top       // #the-id节点的上边界坐标
      res[1].scrollTop // 显示区域的竖直滚动位置
    })
    

    那么,在我们当前的这个需求中,一进入页面就要获取到我们要设置图钉的元素的scrollTop,所以,我们要在data中,先定义一个值,然后在生命周期onload中,获取这个值。

    <script>
    import wepy from 'wepy'
    export default class Index extends wepy.page {
      config = {
        navigationBarTitleText: 'test'
      }
      data = {
        affix: false,
        offsetHeight: 0
      }
    
      computed = {
    
      }
      onPageScroll(e) {
        console.log(e.scrollTop)
        if (e.scrollTop > this.offsetHeight) {
          this.affix = true
        } else {
          this.affix = false
        }
        this.$apply()
      }
      methods = {
      }
      getData() {
      }
      events = {}
    
      onLoad() {
        console.log(this)
        var query = wepy.createSelectorQuery()
        console.log(query)
        query.select('#data').boundingClientRect()
        query.exec((res) => {
          this.offsetHeight = res[0].top
          this.$apply()
          // console.log(wepy)
          // console.log(this.offsetHeight)
          // console.log(this)
        })
      }
    }
    </script>
    

    3. 根据判断的结果,动态修改类

    <style lang="less">
    .affix {
      width: 100%;
      height: 100rpx;
      background-color: #66ccff;
      color: #fff;
    }
    .fix{
      position: fixed;
      top: 0;
    }
    </style>
     <view class="{{affix?'affix fix':'affix'}}"  id="data">
        我是图钉
      </view>
    

    4. 完整代码

    不见惹



    image

    相关文章

      网友评论

          本文标题:微信小程序 wepy中 affix 图钉 吸顶效果实现

          本文链接:https://www.haomeiwen.com/subject/oejtzftx.html