vue公众号项目中的橡皮筋效果

上代码

  • 先定义两个事件,作用都写清楚了
// 滑动开始获取初始位置坐标
    touchstartFunction (e) {
      this.startY = e.touches[0].pageY;
    },

    // 监听手指滑动事件
    touchmoveFunction (e) {
      let el = document.querySelector('.sympt_part');// 需要滑动的dom元素这个为包裹滑动元素的父元素
      if (!e.isSCROLL) {
        e.preventDefault(); // 阻止默认事件(上下滑动)
        console.log('阻止了');
      } else {
        // 需要滑动的区域
        let moveY = e.touches[0].pageY;
        let top = el.scrollTop;
        let ch = el.clientHeight;// 对象最顶端和窗口最顶端之间的距离
        let scrollH = el.scrollHeight; // 含滚动内容的元素大小
        if ((top === 0 && moveY > this.startY) || (top + ch === scrollH && moveY < this.startY)) {
          e.preventDefault();
          console.log('阻止了');
        } else {
          console.log('开启了');
        }
      }
    },
  • 生命周期里
 let ios = navigator.userAgent.indexOf('iphone');// 判断是否为ios
    // 获取触摸坐标
    let _this = this;
    document.body.addEventListener('touchstart', _this.touchstartFunction, { passive: false });
    //
    if (ios === -1) {
      // ios下运行
      let el = document.querySelector('.sympt_part');// 需要滑动的dom元素
      iosTrouchFn(el);
    }
    function iosTrouchFn (el) {
      // el需要滑动的元素
      el.addEventListener('touchmove', function (e) {
        e.isSCROLL = true;
      });
      document.body.addEventListener('touchmove', _this.touchmoveFunction, { passive: false }); // passive防止阻止默认事件不生效
    }
  • 记得结束阶段去掉监听
 beforeDestroy () {
    let _this = this;
    document.body.removeEventListener('touchstart', _this.touchstartFunction, { passive: false });
    document.body.removeEventListener('touchmove', _this.touchmoveFunction, { passive: false });
  }

原理是监听可滚动区域滚动位置,到顶或者到底preventDefault
这个阻止直接写使用在不可能出现滑动的页面,很少这种情况

tips:
如果报touchmove操作失败的错可以同级css里面加上touch-action:none意思是禁止或显示默认菜单等于none会不能滚动,还可以在js里面判断!!e.cancelable

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值