左滑编辑/删除效果

说明

此文梳理模仿QQ好友列表项左滑编辑/删除效果。

result.png

需求

  1. 初始隐藏编辑/删除按钮
    编辑和删除按钮宽度相同
  2. 左滑显示编辑/删除按钮
    左滑距离超过编辑按钮宽度时,才完全显示编辑/删除按钮,否则回弹
  3. 右滑隐藏编辑/删除按钮
    右滑距离超过删除按钮宽度时,才完全隐藏编辑/删除按钮,否则回弹
  4. 当前列表中只能有一个左滑状态,当滑动(左滑/右滑)此列表项之外的其它列表项时,此列表项回到初始状态。

流程图

touch.png

代码

variable

  swipe: ''         // 滑动的样式
  wd: 0            // 编辑和删除按钮的宽度之和
  swipeWd: 0      // 已经滑动的距离
  activeId: ''   // 实际是上一次的活动id

html


        
好友-{{key}}
编辑
删除

script

onPanStart(id) {
        // 获取右侧按钮宽度
        let str = 'editBtn' + id
        this.wd = 2*this.$refs[str][0].offsetWidth
        // 初始化
        if (this.activeId != id) {
          this.swipe = "transform:translateX(0px)"
          this.swipeWd = 0
        }
        this.activeId = id
      },
      onPanMove(event) {
        let deltaX = event.deltaX;
        // 组件向左移动直到最大距离
        if(deltaX < 0 && deltaX > -this.wd) { // 向左滑动
          this.swipe = "transform:translateX(" + deltaX + "px)"
          this.swipeWd = deltaX
        }

        if(deltaX > 0 && deltaX <= this.wd && this.swipeWd < 0) { // 向右滑动
          let wx = deltaX + this.swipeWd
          this.swipe = "transform:translateX(" + wx + "px)"
        }
      },
      onPanEnd(event) {
        // 判断向左移动的距离是否大于二分之一
        let deltaX = event.deltaX;
        if (deltaX < 0) {
          if (deltaX <= - this.wd/2) { // 向左滑动超过二分之一
            this.swipe = "transform:translateX(" + (-this.wd) + "px)"
            this.swipeWd = -this.wd
          } else {
            this.swipe = "transform:translateX(0px)"
            this.swipeWd = 0
          }
        }else {
          if (this.swipeWd < 0 && deltaX >= this.wd/2) { // 向左滑动超过二分之一
            this.swipe = "transform:translateX(0px)"
            this.swipeWd = 0
          } else {
            this.swipe = "transform:translateX(" + this.swipeWd + "px)"
          }
        }
      }

style

.wrap {
    width: 120%; // 超过100%
    transition 0.2s ease 0s // 过渡效果
}

你可能感兴趣的:(左滑编辑/删除效果)