萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

解決 onmousewheel 多次觸發問題:全螢幕滾動切換完整實作

問題背景

實作首屏與第二屏之間滾動滑鼠滾輪整頁切換效果。Chrome 下 onmousewheel 事件會在一次滾動操作中連續觸發多次,導致動畫佇列堆疊、頁面滾動失控。

問題原因分析

  • 使用者一次滾動操作產生多個 wheel 事件(高精度滑鼠/觸控板)
  • 動畫執行期間(animate() 未完成)新事件持續觸發
  • 多個動畫佇列疊加,導致頁面「卡住」無法正常切換

演進過程:三版代碼對比

版本一:原始版(有 Bug)

$(document).ready(function(){
    var height = $(window).height();
    var scrollFunc = function(e){
        var scrollTop = document.body.scrollTop || document.documentElement.scrollTop;
        e = e || window.event;
        
        // 向下滾動:第 1 屏 → 第 2 屏
        if((e.wheelDelta < 0 || e.detail > 0) && scrollTop >= 0 && scrollTop < height){
            $(document.body).animate({scrollTop: height}, "fast");
            $(document.documentElement).animate({scrollTop: height}, "fast");
        }
        // 向上滾動:第 2 屏 → 第 1 屏
        else if((e.wheelDelta > 0 || e.detail < 0) && scrollTop >= height && scrollTop <= height + 20){
            $(document.body).animate({scrollTop: 0}, "fast");
            $(document.documentElement).animate({scrollTop: 0}, "fast");
        }
    };
    
    // 事件註冊
    if(document.addEventListener){
        document.addEventListener('DOMMouseScroll', scrollFunc, false); // Firefox
    }
    window.onmousewheel = document.onmousewheel = scrollFunc; // IE/Chrome/Safari
});

版本二:移除/恢復事件監聽器(改善但冗餘)

var scrollFunc = function(e){
    // 關鍵:動畫開始前移除事件監聽
    document.onmousewheel = undefined;
    
    var scrollTop = document.body.scrollTop || document.documentElement.scrollTop;
    e = e || window.event;
    
    if((e.wheelDelta < 0 || e.detail > 0) && scrollTop >= 0 && scrollTop < height){
        $(document.body).animate({scrollTop: height}, "fast", "linear", function(){
            // 動畫完成後恢復監聽
            document.onmousewheel = scrollFunc;
        });
        $(document.documentElement).animate({scrollTop: height}, "fast", "linear", function(){
            document.onmousewheel = scrollFunc;
        });
    }
    // ... 向上滾動邏輯相同
};

缺點:document.body 與 document.documentElement 兩個動畫各自恢復監聽,可能重複綁定。

版本三:旗標鎖定最終版(推薦)

$(document).ready(function(){
    var height = $(window).height();
    var width = $(window).width();
    
    // 判斷捲軸容器:Firefox/IE 用 documentElement,其他用 body
    var body;
    if(navigator.userAgent.indexOf("Firefox") > 0 || navigator.userAgent.indexOf("MSIE") > 0){
        body = document.documentElement;
    } else {
        body = document.body;
    }
    
    var isFinish = true; // 動畫完成旗標
    
    var scrollFunc = function(e){
        // 關鍵:動畫未完成時直接忽略事件
        if(!isFinish) return;
        
        var scrollTop = body.scrollTop;
        e = e || window.event;
        
        // 向下滾動(預留 20px 緩衝)
        if((e.wheelDelta < 0 || e.detail > 0) && scrollTop >= 0 && scrollTop < height - 20){
            scroll(height);
        }
        // 向上滾動
        else if((e.wheelDelta > 0 || e.detail < 0) && scrollTop >= height && scrollTop <= height + 20){
            scroll(0);
        }
    };
    
    // 統一滾動動畫函式
    var scroll = function(targetTop){
        isFinish = false; // 鎖定
        $(body).animate({
            scrollTop: targetTop
        }, "fast", "linear", function(){
            isFinish = true; // 解鎖
        });
    };
    
    // 事件註冊
    if(document.addEventListener){
        document.addEventListener('DOMMouseScroll', scrollFunc, false);
    }
    document.onmousewheel = scrollFunc;
});

現代標準化方案:Wheel Event + Passive Listeners

const scrollController = (() => {
    const height = window.innerHeight;
    const body = document.scrollingElement; // 統一取得捲軸容器(現代瀏覽器)
    let isAnimating = false;
    
    function scrollTo(target) {
        if (isAnimating) return;
        isAnimating = true;
        
        // 使用 Web Animations API 或 CSS scroll-behavior
        body.animate({ scrollTop: target }, {
            duration: 400,
            easing: 'ease-out'
        }).onfinish = () => { isAnimating = false; };
    }
    
    function onWheel(e) {
        if (isAnimating) return;
        const scrollTop = body.scrollTop;
        const delta = e.deltaY || -e.wheelDelta || e.detail * 40; // 統一 delta
        
        if (delta > 0 && scrollTop < height - 20) {
            scrollTo(height); // 向下
        } else if (delta < 0 && scrollTop >= height) {
            scrollTo(0); // 向上
        }
    }
    
    // passive: true 提升滾動效能,但無法 preventDefault
    // 此處不需 preventDefault,可加入 passive
    window.addEventListener('wheel', onWheel, { passive: true });
    
    return { destroy: () => window.removeEventListener('wheel', onWheel) };
})();

關鍵技術點總結

技術點舊版寫法現代寫法
事件類型onmousewheel / DOMMouseScrollwheel (標準)
Delta 正規化手動判斷 wheelDelta/detaile.deltaY (標準)
捲軸容器UA 判斷 body/documentElementdocument.scrollingElement
防抖/節流旗標鎖定 isFinish旗標 / requestAnimationFrame / 防抖函式
動畫jQuery animate()Web Animations API / CSS scroll-behavior

總結

核心解法是動畫期間忽略後續輪播事件(旗標鎖定或移除監聽器)。現代專案建議使用標準 wheel 事件、document.scrollingElement、Web Animations API,並善用 passive: true 提升滾動效能。

copyright © 萬盛學電腦網 all rights reserved