H5左侧滑动返回上一个页面

<template>
  <div class="touch-back-page">
    <div class="left-side" @touchstart.stop="handleTouchStart" @touchend.stop="handleTouchEnd" v-if="leftDrag"></div>
    <div class="right-side" @touchstart.stop="handleTouchStart" @touchend.stop="handleTouchEnd" v-if="rightDrag"></div>
  </div>
</template>

<script>
export default {
  name: 'touchBack',
  data() {
    return {
      startPosX: 0, // 触碰开始位置
      direction: 'left', // 滑动方向
      windowWidth: document.body.offsetWidth, // 屏幕宽度
    };
  },
  props: {
    // 左侧滑动
    leftDrag: {
      type: Boolean,
      default: true,
    },
    // 右侧滑动
    rightDrag: {
      type: Boolean,
      default: false,
    },
  },
  methods: {
    // 触碰开始
    handleTouchStart(e) {
      if (!e.touches) {
        return;
      }
      this.startPosX = e.touches[0].clientX;
      this.direction = this.startPosX > this.windowWidth / 2 ? 'right' : 'left';
    },
    // 触碰结束
    handleTouchEnd(e) {
      if (!e.changedTouches || !e.changedTouches[0]) {
        return;
      }

      let x = e.changedTouches[0].clientX;
      const offset = x - this.startPosX;
      const canDrag = (this.direction === 'left' && offset >= 50) || (this.direction === 'right' && offset <= -50);
      if (canDrag) {
        this.startPosX = 0;
        this.$emit('goBack');
      }
    },
  },
};
</script>

<style scoped lang="less">
.touch-back-page {
  > div {
    position: fixed;
    top: 0;
    bottom: 0;
    width: 30px;
    opacity: 0.01;
    z-index: 10000;
  }
  .left-side {
    left: 0;
  }
  .right-side {
    right: 0;
  }
}
</style>

注意:

由于是页面的左右两侧开启了30px的宽度用来作为用户左右滑的事件触发层,因此在这个位置的点击或者其他事件会失效。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值