jQuery手风琴,将点击标签的开头滚动到顶部,如果展开的标签位于被点击的标签上方,则无法使用?

And*_*eas 7 jquery jquery-ui accordion scrollto scrolltop

让我的jquery手风琴做我想做的事情有点问题.

我总是希望点击的标签从页面顶部滚动到固定数量的像素,我有点工作.但是,只要活动选项卡位于单击的选项卡上方,并且页面已经向下滚动一点,所单击选项卡的顶部和部分内容就会向上滚动超过页面顶部.

这就是我得到的:

$(function() {
    $("#accordion").accordion({
        autoHeight: false,
        collapsible: true,
        heightStyle: "content",
        active: 0,
        animate: 300
    });
    $('#accordion h3').bind('click',function(){
        theOffset = $(this).offset();
        $('body,html').animate({ 
            scrollTop: theOffset.top - 100 
        });
    });
});
Run Code Online (Sandbox Code Playgroud)

这是一个解释我的问题的小提琴,

例如,展开"第2部分",向下滚动并单击"第3部分"选项卡,它将全部滚动到页面外,其他方式可以正常工作.

如果在打开一个新选项之前关闭活动选项卡它也可以正常工作,所以我假设这与崩溃选项卡的高度有关,这会使滚动到顶部功能!?

希望有人可以提供帮助,我可能会采取错误的方法.我真的不知道我在做什么,因为我的jquery技能仅限于基本的切割粘贴理解!^^

在此先感谢,所有的帮助和指针区域更受欢迎!:)

干杯

tec*_*bar 16

是的,它被关闭的标签的高度是导致问题的原因.

由于其上方的标签折叠,所以点击的h3的顶部会立即发生变化.

解决方法(可能是坏的)是在崩溃动画完成后触发滚动动画,即如果折叠动画设置为300ms,则在310ms之后开始滚动动画.

$(function() {
        $("#accordion").accordion({
            autoHeight: false,
            collapsible: true,
            heightStyle: "content",
            active: 0,
            animate: 300 // collapse will take 300ms
        });
        $('#accordion h3').bind('click',function(){
            var self = this;
            setTimeout(function() {
                theOffset = $(self).offset();
                $('body,html').animate({ scrollTop: theOffset.top - 100 });
            }, 310); // ensure the collapse animation is done
        });
});
Run Code Online (Sandbox Code Playgroud)

更新小提琴

  • @Technotronic - 因为setTimeout回调中的`this`的值不是它在外面的值. (2认同)

Red*_*ght 5

您可以向手风琴添加激活的功能。这样,一旦其他显示/隐藏动画完成,它就会触发。

$(function() {
    $("#accordion").accordion({
        autoHeight: false,
        collapsible: true,
        heightStyle: "content",
        active: 0,
        animate: 300,
        activate: function(event, ui) {
            try {
                theOffset = ui.newHeader.offset();
                $('body,html').animate({ 
                    scrollTop: theOffset.top 
                });
            } catch(err){}
        }
    });
});
Run Code Online (Sandbox Code Playgroud)

如果您要折叠打开的手风琴选项卡,则需要尝试捕获,因为 ui.newHeader 未定义。