-->

JQuery animation lag when scrolling

2020-04-09 23:57发布

问题:

I have a header minimise when I scroll down, however I have a lag for it returning to full size upon returning back to the top of the page. Seems to be worse when I scroll further.

The Javascript I have:

$(document).ready(function () {
    $("header").animate({
        height: "140px"
    }, 200);
    $("header>h2").show(200);
});

$(window).scroll(function () {
    if ($(document).scrollTop() > 0) {
        $("header").animate({
            height: "70px"
        }, 200);
        $("header>h2").hide(200);
    } else {
        $("header").animate({
            height: "140px"
        }, 200);
        $("header>h2").show(200);
    }
});

I don't appear to get the same problem if I set the animation time to 0 which is why I'm assuming that it's the animations that are the issue.

Is there some kind of inherent lag associated with them, like it having to wait until one's finished to do the next? If so (or any other reason for it) is it possible to overcome it and still have the animations?

There's a JSFiddle here

回答1:

The issue is that each time you scroll, an animation is triggered with a 200ms transition. These queue up and process one by one which is why you see the lag. You can stop any existing animations on each scroll:

$("header").stop();

Your full code:

$(document).ready(function () {
    $("header").animate({
        height: "140px"
    }, 200);
    $("header>h2").show(200);
});

$(window).scroll(function () {
    $("header").stop();
    if ($(document).scrollTop() > 0) {
        $("header").animate({
            height: "70px"
        }, 200);
        $("header>h2").hide(200);
    } else {
        $("header").animate({
            height: "140px"
        }, 200);
        $("header>h2").show(200);
    }
});

Fiddle here: http://jsfiddle.net/u06sg6a2/



回答2:

This is happening because the scroll event is called constantly, thus the animation function is called as well. But this is not necessary, since once the scrollTop is greater that 0 and the header is hidden, the header will remain like that and there is no reason to animate. One simple solution is to modify the code with something like the following,

http://jsfiddle.net/v6rspv0k/

$(document).ready(function () {
    $("header").animate({
        height: "140px"
    }, 200);
    $("header>h2").show(200);
});
var headerNotShown = false;
$(window).scroll(function () {
    if (!headerNotShown&&$(document).scrollTop() > 0) {
        console.log("animation1");
        $("header").animate({
            height: "70px"
        }, 200);
        $("header>h2").hide(200);
        headerNotShown = true;
    } else if(headerNotShown&&$(document).scrollTop() ===0){
        console.log("animation2");
        $("header").animate({
            height: "140px"
        }, 200);
        $("header>h2").show(200);
        headerNotShown=false;
    }
});