微信小程序scroll-view详解及案例

2023-03-27 18:58:56

需求:实现类似美团外卖。
1.点击左侧菜单右侧滚动到对应内容。
2.滚动右侧内容左侧对应菜单高亮。

一、首先介绍下scroll-view

可滚动视图区域。

以下属性1.0.0版本即可

属性 类型 默认值 必填 说明
scroll-y boolean false 允许纵向滚动
scroll-into-view string 值应为某子元素id(id不能以数字开头)。设置哪个方向可滚动,则在哪个方向滚动到该元素
scroll-with-animation boolean false 在设置滚动条位置时使用动画过渡
bindscroll eventhandle 滚动时触发,event.detail = {scrollLeft, scrollTop, scrollHeight, scrollWidth, deltaX, deltaY}

二、案例
先来看下菜单的页面代码:

`<scroll-view scroll-y='true' class='nav'>
    <view wx:for='{{list}}'  wx:key='{{item.id}}'data-id='{{item.id}}'
class='navList {{currentIndex==index?"active":""}}' bindtap="listClick" data-index='{{index}}'>{{item.name}}</view>
  </scroll-view>`

1.设置scroll-y让其可上下滚动。
2.自定义属性id的值,通过id实现与右侧对应。
3.通过currentIndex实现获取当前处于哪个菜单下并设置高亮样式并自定义index值。
4.添加点击事件listClick,方法如下:

 `listClick:function(e){
    let me=this;
    me.setData({
      activeList:e.target.dataset.id,
      currentIndex:e.target.dataset.index
    })
  }, `

该方法实现记录当前点击了哪个菜单。通过activeList(即自定义的id属性)实现右侧内容滚动到对应位置。currentIndex作用上文有提到。

再来看下右侧内容代码:

`<scroll-view scroll-y='true' scroll-into-view='{{activeList}}' scroll-with-animation='true' bindscroll='scrollFunc' class='content' style='height:400rpx'>
    <view class="fishList" wx:for='{{content}}' id='{{item.id}}' wx:key='{{item.id}}'>
      <p>{{item.name}}</p>
    </view>
  </scroll-view>`

1.scroll-into-view 即定义要滚动到哪里。scroll-into-view='{{activeList}}'
2.activeList 为点击左侧菜单时获取到的id值,定义 id='{{item.id}}' 
此时即可实现点击左侧菜单,右侧滚动到对应位置。

下一步实现如何滚动右侧内容左侧对应菜单高亮:
1.在data中定义,实际开发中高度需计算得到
2.在要滚动的右侧scroll-view中定义bindscroll,即滚动时调用的方法。

实现如下:

`scrollFunc:function(e){
    this.setData({
      scrollTop:e.detail.scrollTop
    })
    for (let i = 0; i < this.data.heightList.length; i++) {
        let height1 = this.data.heightList[i];
        let height2 = this.data.heightList[i + 1];
      if (!height2 || (e.detail.scrollTop >= height1 && e.detail.scrollTop < height2)) {
          this.setData({
            currentIndex: i
          })
          return;
        }
      }
      this.setData({
        currentIndex: 0
      })
  },`

实现基本思路:比较滚动上去的高度和右侧每块的高度,如果在某个模块之中,对应该模块的菜单高亮,即设置currentIndex

如果你想开发小程序或者了解更多小程序的内容,可以通过专业开发公司,来帮助你实现开发需求:厦门在乎科技-专注厦门小程序开发、APP开发、网站开发、H5小游戏开发 

  • 作者:厦门在乎科技
  • 原文链接:https://blog.csdn.net/weixin_41996102/article/details/120369185
    更新时间:2023-03-27 18:58:56