touch事件

 touch事件

<template>
  <div
    class="scrollview"
    @touchstart="touchstart"
    @touchmove="touchmove"
    @touchend="touchend"
    @touchcancel="touchcancel"
  >
    <div class="container" ref="container" :class="{ani:isAni}" :style="containerLeft">
      <slot></slot>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 记录上一个触摸事件的x坐标
      lastPointX: 0,
      // 当前容器container的横坐标偏移量
      x: 0,
      // 是否有动画
      isAni: false
    };
  },
  computed: {
    containerLeft() {
      return {
        left: this.x + "px"
      };
    }
  },
  methods: {
    touchstart(e) {
      this.isAni = false;
      // console.log("touchstart:手指触摸屏幕的一瞬间触发");
      // e.touches:是一个列表,表示当前屏幕的触摸点(有几个手指摁到屏幕上了)
      // e.touches[0].pageX:当前触摸点距离屏幕左边的距离
      this.lastPointX = e.touches[0].pageX;
    },
    touchmove(e) {
      this.isAni = false;
      // console.log("touchmove:手指在屏幕上触摸移动时触发");
      var nowPointX = e.touches[0].pageX;
      var offset = nowPointX - this.lastPointX;
      // 判断边界问题
      if (
        this.x >= 0 ||
        this.x <= this.$el.clientWidth - this.$refs.container.clientWidth
      ) {
        this.x = this.x + offset / 2;
      } else {
        this.x = this.x + offset;
      }
      this.isAni = true;
      // 重置lastPointX
      this.lastPointX = nowPointX;
    },
    touchend(e) {
      this.isAni = false;
      // console.log("touchend:手指离开屏幕的一瞬间触发");
      // 判断边界问题
      if (this.x >= 0) this.x = 0;
      if (this.x <= this.$el.clientWidth - this.$refs.container.clientWidth)
        this.x = this.$el.clientWidth - this.$refs.container.clientWidth;
      // 整页翻
      this.x =
        Math.round(this.x / this.$el.clientWidth) * this.$el.clientWidth +
        16 * Math.round(this.x / this.$el.clientWidth);
    },
    touchcancel(e) {
      // console.log("touchcancel:触摸事件被迫取消(结束)")
    }
  }
};
</script>

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值