How to stick fixed div of height more than viewport to body

后端 未结 5 945
生来不讨喜
生来不讨喜 2021-01-18 05:50

I know about the positioning of div (fixed, absolute and relative). I can attach a fixed div to body so that it will stick to the same position while scrolling body. Here I

5条回答
  •  伪装坚强ぢ
    2021-01-18 06:35

    That is possible by placing your sidebar absolute and change that to fixed as soon as the windows scroll position passes the bottom.

    The CSS:

    #sidebar {
        height: 120%;
        width: 100px;
        border: 2px solid blue;
        padding: 20px;
        margin: 20px;
        position: absolute;
        top: 0;
    }
    

    The jQuery:

    $(document).ready(function() {
        var bottomPos = $('#sidebar').outerHeight(true) - $(window).height();
        $(window).scroll( function() {
            if ( $(window).scrollTop() > bottomPos ) {
                $('#sidebar').css({'position':'fixed','top':'auto','bottom':'0px'});
            } else {
                $('#sidebar').css({'position':'absolute','top':'0px'});
            }
        });
    });
    

    And a demo.

提交回复
热议问题