簡體   English   中英

使用JavaScript進行滾動動畫后的跳動滾動

[英]Jumpy scroll after scroll-animation with javascript

滾動動畫有問題。 滾動動畫后滾動頁面時,會發生跳動滾動。 我懷疑滾動事件會重復發生,但是我不確定。 你能幫我嗎?

$(document).ready(function(){
var offset;
var anchor = $("#navigation").offset().top;  
$(window).bind('mousewheel', function (e) {
offset = $(window).scrollTop();

if (e.originalEvent.wheelDelta < 0) {
    //mouse scroll down
    console.log('Down: ' + offset + " " + anchor);

    if (offset >= anchor) {
        // if anchor has been scrolled, user can scroll further
        // the problem ocuurs in this block
        return true;
    } else {
        // animate to anchor( nav menu)
        $("body, html").animate({
            scrollTop: anchor + 1
        }, 200);
        $("#navigation").addClass("nav-fixed");
        return false;
    }
} else {
    //mouse scroll up
    if (offset < anchor) {
        $("#navigation").removeClass("nav-fixed");
        return true;
    }
}});

});

JSFiddle: http : //jsfiddle.net/0noms3cs/

非常感謝!

您的問題很簡單。 滾動事件一遍又一遍地觸發。 您在導致此問題的原因上的思路是正確的,您有大量animate事件堆積起來,從而導致這種奇怪的行為。

您可以通過添加一個布爾變量(例如scrollInitialized )解決此問題,該變量以false開頭,並且一旦滾動事件觸發一次,該布爾變量就會翻轉為true

這是修改后的JS代碼。 注意:我僅在if語句中添加了scrollInitialized變量並對其進行了檢查。

編輯 :我也刪除了內部if-else情況,因為使用此設計是不必要的。

編輯2 :我最初誤解了您想做什么。 您需要做的是添加一個scrollLock變量,該變量僅在動畫期間設置為true 考慮了這一點后,我為您實現了它。 這是Jsfiddle:

https://jsfiddle.net/04gaaapo/1/

這是新的JS代碼:

$(document).ready(function () {

    var scrollLock = false;
    var offset;
    var anchor = $("#navigation").offset().top;

    $(window).bind('mousewheel', function (e) {
        offset = $(window).scrollTop();

        // if scroll is NOT locked and we are above the anchor
        if (scrollLock === false && offset < anchor) {
            if (e.originalEvent.wheelDelta < 0) {
                // scrolling down
                scrollLock = true;

                // animate to anchor( nav menu)
                $("body, html").animate({
                    scrollTop: anchor + 1
                }, 200);

                // unlock in 250ms
                setTimeout(toggleLock, 250);

                // add nav class
                $("#navigation").addClass("nav-fixed");

            } else if (e.originalEvent.wheelDelta > 0) {
                // scrolling up
                scrollLock = true;

                // animate to top of page
                $("body, html").animate({
                    scrollTop: 0
                }, 200);

                // unlock in 250ms
                setTimeout(toggleLock, 250);

                // remove nav class
                $("#navigation").removeClass("nav-fixed");

            }
        }

    });

    function toggleLock() {
        scrollLock = !scrollLock;
    };

});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM