触发滑动方向锁(vue音乐项目)

465 阅读1分钟

当触摸滑动时,x和y都会滑动,我们只想要一个方向滑动的时候就利用方向锁

例如

image.png

这里我们只需要水平的滑动

所以创建一个变量来判断水平和竖直哪个距离大,来锁定滚动的方向

function onMiddleTouchStart (e) {
    touch.startX = e.touches[0].pageX
    touch.startY = e.touches[0].pageY
    touch.directionLocked = ''
  }

  function onMiddleTouchMove (e) {
    // 滑动偏移量
    const deltaX = e.touches[0].pageX - touch.startX
    const deltaY = e.touches[0].pageY - touch.startY
    
    // 给偏移量取绝对值
    const absdeltaX = Math.abs(deltaX)
    const absdeltaY = Math.abs(deltaY)

    // 判读滑动方向
    if (!touch.directionLocked) {
      touch.directionLocked = absdeltaX >= absdeltaY ? 'h' : 'v'
    }
    如果是y方向就跳出触摸函数
    if (touch.directionLocked === 'v') {
      return
    }