jQuery scroll to top of DIV that is opening

2019-08-27 09:09发布

问题:

I have an accordion that opens and closes open clicking. The problem I have is that I want the page to scroll to the top of div when it's clicked on. What I have doesn't quite work, it scrolls to where the top of div was when clicked on, not where it is. My jQuery code is:

$(".aro > .wrap").click(function () {
        if (!$(this).parent().hasClass("active")) {
        $(".active .details").slideUp("slow");
        $(".aro").removeClass("active");
        $(this).parent().addClass("active");
        $(this).parent().children(".details").slideDown("slow");
        }
        else {
            $(this).parent().removeClass("active");
        $(this).parent().children(".details").slideUp("slow");
        }
        $('html, body').animate({
        scrollTop: $(this).offset().top
    }, 2000);
});

I made a simple JSFiddle at: http://jsfiddle.net/489Y2/1/
Anyone know what I'm doing wrong?

回答1:

The issue is that the animate method is being fired while the slideDown is still running, thus it is taking the position at that point in time as where it should scroll to.

The easiest way to fix this is to place the animate into a callback that runs after the slideDown is completed like so:

$(".aro > .wrap").click(function () {
    if (!$(this).parent().hasClass("active")) {
        $(".active .details").slideUp("slow");
        $(".aro").removeClass("active");
        $(this).parent().addClass("active");
        $(this).parent().children(".details").slideDown("slow", function() {
            $('html, body').animate({
                scrollTop: $(this).parent().offset().top
            }, 2000);
        });
    } else {
        $(this).parent().removeClass("active");
        $(this).parent().children(".details").slideUp("slow");
    }
});

Here is an updated jsFiddle.

Note that I have updated the selector from which the code obtains the offset top, as $(this) within the callback refers to $(".details").