Code前端首页关于Code前端联系我们

微信小程序开发:实现左右滑动卡片的效果

terry 2年前 (2023-09-23) 阅读数 68 #移动小程序
微信小程序开发:实现卡片左右滑动效果

Idea

从上面的效果图来看,基本要求包括:

  • 左右滑动一定距离,然后移动卡片的位置卡在相应的方向。
  • 移动卡片时有一定的加速度。
  • 如果滚动距离太小,它会停留在当前选项卡上并弹跳。

对于不熟悉小程序的同学来说,看到这样的需求可能会有点不安。首先需要计算出卡片的位置,然后设置滑块的位置移动到指定的位置,并且在滑动的过程中添加一个小的加速度...

但是当你看开发的时候小程序,看完文档你会发现小程序是提前给我们写好的,我们只需要进行相应的设置即可。

实现

滚动显示

左右滚动实际上是水平方向滚动。小程序为我们提供了 scroll-view 组件,我们可以通过设置 scroll-x 属性使其水平滚动。 ?

该值应该是子元素的特定id(标识符不能以数字开头)。设置哪个方向可以滚动,然后到哪个方向的元素scroll-with-animationboole和设置滑块位置时使用动画过渡

有了以上两个属性,我们会没事的。只要每张卡片都有自己的页面,并设置元素ID,就可以轻松实现页面旋转效果。

通过左右滑动来判断

这里我们根据触摸的起始和结束位置来确定滚动方向。

微信小程序为我们提供了touchstart和touchend事件。我们可以通过考虑起点和终点的线段来确定方向。

代码实现

说话很便宜,给我看看代码。

  • card.wxml
<scroll-view class="scroll-box" scroll-x scroll-with-animation
  scroll-into-view="{{toView}}"
  bindtouchstart="touchStart"
  bindtouchend="touchEnd">
    <view wx:for="{{list}}" wx:key="{{item}}" class="card-box" id="card_{{index}}">
      <view class="card">
        <text>{{item}}</text>
      </view>
    </view>
</scroll-view>
复制代码
  • card.wxss
page{
  overflow: hidden;
  background: #0D1740;
}
.scroll-box{
  white-space: nowrap;
  height: 105vh;
}

.card-box{
  display: inline-block;
}

.card{
  display: flex;
  justify-content: center;
  align-items: center;
  box-sizing: border-box;
  height: 80vh;
  width: 80vw;
  margin: 5vh 10vw;
  font-size: 40px;
  background: #F8F2DC;
  border-radius: 4px;
}
复制代码
  • card.js
const DEFAULT_PAGE = 0;

Page({
  startPageX: 0,
  currentView: DEFAULT_PAGE,
  data: {
    toView: `card_${DEFAULT_PAGE}`,
    list: ['Javascript', 'Typescript', 'Java', 'PHP', 'Go']
  },

  touchStart(e) {
    this.startPageX = e.changedTouches[0].pageX;
  },

  touchEnd(e) {
    const moveX = e.changedTouches[0].pageX - this.startPageX;
    const maxPage = this.data.list.length - 1;
    if (Math.abs(moveX) >= 150){
      if (moveX > 0) {
        this.currentView = this.currentView !== 0 ? this.currentView - 1 : 0;
      } else {
        this.currentView = this.currentView !== maxPage ? this.currentView + 1 : maxPage;
      }
    }
    this.setData({
      toView: `card_${this.currentView}`
    });
  }
})
复制代码
  • Goldcard.json链接:https://juejin .im/post/5cc7fc4c6fb9a0324a08b874
    来源:掘金
    版权归作者所有。商业转载请联系作者获取授权。非商业转载请注明出处。

版权声明

本文仅代表作者观点,不代表Code前端网立场。
本文系作者Code前端网发表,如需转载,请注明页面地址。

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

热门