阻止 iOS 雙擊頁面上/下滑動(dòng)

參考文章:
禁止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 的代碼:

GitHub 地址

/**
 * @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());
        }
    }
};
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容