上代码
- 先定义两个事件,作用都写清楚了
// 滑动开始获取初始位置坐标
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