微信小程序第六篇:元素吸顶效果实现

 系列文章传送门:

微信小程序第一篇:自定义组件详解

微信小程序第二篇:七种主流通信方法详解

微信小程序第三篇:获取页面节点信息

微信小程序第四篇:生成图片并保存到手机相册

微信小程序第五篇:页面弹出效果及共享元素动画

话不多说,先看效果:

这种效果在我们日常开发中是非常常见的,下面让我们结合代码一起来看看是如何实现的吧。

js 部分数据:

data: {
    content: {
      value: '啦啦啦',
      isShow: false
    },
    message: [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20],
    mainHeight: app.globalData.wHeight - app.globalData.headerHeight
  },
 

wxml部分代码: 

<template name="scrollData">
    <view style="height: 100rpx; width: 90%;margin: 20rpx auto;background-color: rgb(172, 212, 219);">
        {
   
   {item}}
    </view>
</template>

<view>
    <header bg="{
   
   {'transparent'}}">YinJie</header>
    <view style="height: 60rpx;width: 100%;background-color: pink;text-align: center;font-size: 22rpx;position: fixed;z-index: 999;"
      wx:if="{
   
   {content.isShow}}"
    >
        {
   
   {content.value}}
    </view>  
    <scroll-view class="" scroll-y="true" bindscroll="scroll" enable-flex="true" style="height: {
   
   {mainHeight}}rpx;">
        <view style="height: 400rpx; width:90%; margin: 0 auto; background-color: grey">
        </view>
        <view style="height: 60rpx;width: 100%;background-color: pink;text-align: center;font-size: 22rpx;margin-top: 20rpx;">
            啦啦啦
        </view>
        <template is="scrollData" data="{
   
   {item}}" wx:for="{
   
   {message}}" wx:key="index"></template>
    </scroll-view>
</view>

我们要实现“啦啦啦”所在的元素块在移动到它的时候吸顶,那必然需要结合 scroll-view 标签的 bindscroll 属性实现,吸顶的关键就是我们在header标签下写一个和要吸顶元素一模一样的wxml元素。通过 wx:if 来控制它的显示与隐藏,当页面移动到“啦啦啦”所在位置的时候显示这个元素,并且让他的 position 为 fixed,这样就巧妙实现了元素的吸顶效果。

  scroll: function(e) {
      if (e.detail.scrollTop >= 216) {
        if (!this.data.content.isShow) {
          this.setData({
            'content.isShow': true
          })
        }
      } else {
        if (this.data.content.isShow) {
          this.setData({
            'content.isShow': false
          })
        }
      }
  },

当页面距离顶部高度超过 216 也就是 “啦啦啦” 所在元素高度时,就让 header 下的元素显示。反之,当页面距离顶部高度小于 216 时再让他隐藏就可以啦!

猜你喜欢

转载自blog.csdn.net/qq_49900295/article/details/128257059