jQuery accordion, scroll beginning of clicked tab to the top, doesn't work if expanded tab is above the one being clicked?

[亡魂溺海] 提交于 2019-11-30 07:25:19

Yes, its the height of the tab thats getting closed thats the cause of the issue.

The top of the clicked h3 changes immediately afterwards due to the collapsing of a tab above it.

A workaround (a bad one perhaps), is to trigger the scroll animation after the collapse animation finishes, i.e. if the collapse animation is set for 300ms, start off the scroll animation after 310ms or something.

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

Updated Fiddle

RedEight

You can add an activated function to the accordion. That way it triggers once the other show/hide animations have completed.

$(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){}
        }
    });
});

the try catch is required as ui.newHeader is undefined if you are collapsing an open accordion tab.

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