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

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

    It can be done by testing the scrollTop() against the heights of the containers.

    var $sidebar   = $("#sidebar"),
          $window    = $(window),
          offset     = $sidebar.offset(),
          topPadding = 50,
          calc= 0,
          max = 0;
    
    $window.scroll(function() {
        calc = $window.scrollTop() + $sidebar.height() + offset.top;
        if(calc > $('#main').height()) {
              max = $('#main').height() - $sidebar.height();
              $sidebar.stop().css('marginTop', max);
        } else if ($window.scrollTop() > offset.top) {
          $sidebar.stop().animate({
            marginTop: $window.scrollTop() - offset.top
          });
        } else {
          $sidebar.stop().animate({
            marginTop: 0 
          });
        }
    });
    #wrapper {
        width: 100%;
    }
    
    #main, #more {
        width:70%;
        background-color: black;
        color:white;
        height: 900px;
        float:left;
    }
    
    #more {
        background-color: red;
    }
    p {
        margin-top:50%;
    }
    #sidebar {
        width:30%;
        background-color: blue;
        color:white;
        height: 500px;
        float:left;
    }
    
    

    Main Content

    More Content

提交回复
热议问题