jQuery滚动到即将打开的DIV的顶部 [英] jQuery scroll to top of DIV that is opening

查看:88
本文介绍了jQuery滚动到即将打开的DIV的顶部的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个手风琴,可以打开和关闭打开的点击声。我遇到的问题是,我希望页面在单击时滚动到div的顶部。我所拥有的还不够用,它滚动到单击div时的顶部位置,而不是它所在的位置。我的jQuery代码是:

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);
});

我在以下位置做了一个简单的JSFiddle: http://jsfiddle.net/489Y2/1/

任何人都知道我在做什么错吗?

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

推荐答案

问题是在 slideDown时会触发 animate 方法仍在运行,因此它将在该时间点上滚动到该位置。

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.

最简单的解决方法是将 animate 放入在 slideDown 完成后运行的回调中,如下所示:

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");
    }
});

这里是更新的 jsFiddle

请注意,我已经更新了选择器,代码从该选择器获取了偏移量的顶部,如 $(this)表示 $(。details)

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

这篇关于jQuery滚动到即将打开的DIV的顶部的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆