參考文章:
禁止IOS雙擊上滑
當(dāng)在UIWebView上雙擊時(shí)防止網(wǎng)頁滾動(dòng)
背景
在 iOS 系統(tǒng)下,雙擊網(wǎng)頁會(huì)觸發(fā)整個(gè)網(wǎng)頁的上/下滑動(dòng),在某些情況下,需要阻止這種默認(rèn)行為
解決思路
監(jiān)聽 body 的 touchend 事件,并記錄上一次點(diǎn)擊的時(shí)間戳;
每一次觸發(fā) touchend 事件的時(shí)候,通過對(duì)比上一次的時(shí)間戳,計(jì)算出兩次 touchend 的時(shí)間間隔,如果時(shí)間間隔小于雙擊的時(shí)間間隔(300ms),則阻止瀏覽器默認(rèn)事件(e.preventDefault)。
以下為 vue mixin 的代碼:
/**
* @file 阻止 iOS 默認(rèn)雙擊上/下滑 mixin;僅在 iOS 下有效
* @author wangkai37<waka931124@gmail.com>
*/
// 雙擊時(shí)間間隔
const DOUBLE_TAP_TIME_INTERVAL = 300;
export default {
beforeDestory() {
if (this.isIOS() && this.flagStopIOSDoubleTapMixin) {
this.removeOrientationListenerMixin();
}
},
methods: {
// 添加事件 body touchend 監(jiān)聽
addBodyTouchendListenerStopIOSDoubleTapMixin() {
if (!this.isIOS()) {
return;
}
// 記錄上次觸摸的時(shí)間
this.lastTouchTimeStopIOSDoubleTapMixin = null;
// 標(biāo)志位
this.flagStopIOSDoubleTapMixin = true;
// 監(jiān)聽 document.body 的 touchend 事件
document.body.addEventListener('touchend', this.bodyTouchendListenerStopIOSDoubleTapMixin, false);
},
// 移除事件 body touchend 監(jiān)聽
removeBodyTouchendListenerStopIOSDoubleTapMixin() {
if (!this.isIOS()) {
return;
}
// 標(biāo)志位
this.flagStopIOSDoubleTapMixin = false;
// 移除監(jiān)聽
document.body.removeEventListener('touchend', this.bodyTouchendListenerStopIOSDoubleTapMixin);
},
bodyTouchendListenerStopIOSDoubleTapMixin(e) {
if (!this.isIOS()) {
return;
}
// 當(dāng)前觸摸的時(shí)間戳
let curTouchTime = new Date().getTime();
// 如果上次觸摸的時(shí)間不存在
if (!this.lastTouchTimeStopIOSDoubleTapMixin) {
this.lastTouchTimeStopIOSDoubleTapMixin = curTouchTime;
}
// 時(shí)間差值
let timeDiff = curTouchTime - this.lastTouchTimeStopIOSDoubleTapMixin;
if (timeDiff < DOUBLE_TAP_TIME_INTERVAL && timeDiff > 0) {
// 阻止 iOS 雙擊默認(rèn)滑動(dòng)的行為
e.cancelable && e.preventDefault();
return false;
}
this.lastTouchTimeStopIOSDoubleTapMixin = curTouchTime;
},
isIOS() {
return /(iphone|ipod|ipad)/.test(navigator.userAgent.toLowerCase());
}
}
};