jQuery scroll to top of DIV that is opening

别等时光非礼了梦想. 提交于 2019-12-25 02:57:16

问题


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").



来源:https://stackoverflow.com/questions/24772195/jquery-scroll-to-top-of-div-that-is-opening

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!