How can I check if a scrollbar is visible?

后端 未结 19 2798
情话喂你
情话喂你 2020-11-22 14:39

Is it possible to check the overflow:auto of a div?

For example:

HTML

19条回答
  •  情深已故
    2020-11-22 15:30

    Works on Chrome, Edge, Firefox and Opera, at least in the newer versions.

    Using JQuery...

    Setup this function to fix the footer:

    function fixFooterCaller()
    {
        const body = $('body');
        const footer = $('body footer');
    
        return function ()
        {
            // If the scroll bar is visible
            if ($(document).height() > $(window).height())
            {
                // Reset
                footer.css('position', 'inherit');
                // Erase the padding added in the above code
                body.css('padding-bottom', '0');
            }
            // If the scrollbar is NOT visible
            else
            {
                // Make it fixed at the bottom
                footer.css('position', 'fixed');
                // And put a padding to the body as the size of the footer
                // This makes the footer do not cover the content and when
                // it does, this event fix it
                body.css('padding-bottom', footer.outerHeight());
            }
        }
    }
    

    It returns a function. Made this way just to set the body and footer once.

    And then, set this when the document is ready.

    $(document).ready(function ()
    {
        const fixFooter = fixFooterCaller();
    
        // Put in a timeout call instead of just call the fixFooter function
        // to prevent the page elements needed don't be ready at this time
        setTimeout(fixFooter, 0);
        // The function must be called every time the window is resized
        $(window).resize(fixFooter);
    });
    

    Add this to your footer css:

    footer {
        bottom: 0;
    }
    

提交回复
热议问题