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

后端 未结 5 944
生来不讨喜
生来不讨喜 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:33

    With absolute position (in fixed position we have to hide scroll and set scrollTop instead of top):

    $(document).scroll( function() {
        var offset = $(this).scrollTop() + $(window).height() - $('#sidebar').outerHeight();
        $('#sidebar').css('top', Math.max(0, offset));
    });
    * {
        margin: 0;
        padding: 0;
    }
    
    #content {
        height: 2000px;
        padding-right: 40%;
        background: red;
    }
    
    #sidebar {
        height: 1000px;
        position: absolute;
        width: 40%;
        top: 0; right: 0;
        background: orange;
    }
    
    

    fiddle

提交回复
热议问题