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

后端 未结 2 1924
生来不讨喜
生来不讨喜 2020-12-30 12:53

Got a little bit of a problem with getting my jquery accordion to do what I want.

I always want the tab that is being clicked to be scrolled to a fixed amount of pix

相关标签:
2条回答
  • 2020-12-30 13:12

    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.

    0 讨论(0)
  • 2020-12-30 13:18

    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

    0 讨论(0)
提交回复
热议问题