vue中禁止ios橡皮筋效果(亲测有效)

相信有很多前端的朋友都遇到过这个问题,这个问题真的很头疼。ios的橡皮筋效果会带来一些莫名其妙的bug。如果直接对body禁止的话,那整个页面都无法滑动了。所以我今天带来一个解决方案。原博客找不到了,这是我重新改良的代码(T_T)
首先在methods中定义两个方法

// 滑动开始获取初始位置坐标
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(‘开启了’);
}
}
},
在这里插入图片描述
然后在mounted生命周期函数中添加事件监听

// 禁止ios橡皮筋效果(弹簧效果)
// ********************
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 });
在这里插入图片描述

`

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值