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

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

    Here you have three tutorials for the intended task (first results out of google with query: "fixed sidebar on scroll")

    http://www.waypointarts.com/blog/2013/06/29/fixing-a-side-bar-while-scrolling-until-bottom

    http://andrewhenderson.me/tutorial/jquery-sticky-sidebar/

    http://css-tricks.com/scrollfollow-sidebar/

    Here is the code for one of the approaches:

    CSS

    #page-wrap { 
      width: 600px; 
      margin: 15px auto; 
      position: relative; 
    }
    
    #sidebar { 
      width: 190px; 
      position: fixed; 
      margin-left: 410px; 
    }
    

    jQuery

    $(function() {
    
        var $sidebar   = $("#sidebar"), 
            $window    = $(window),
            offset     = $sidebar.offset(),
            topPadding = 15;
    
        $window.scroll(function() {
            if ($window.scrollTop() > offset.top) {
                $sidebar.stop().animate({
                    marginTop: $window.scrollTop() - offset.top + topPadding
                });
            } else {
                $sidebar.stop().animate({
                    marginTop: 0
                });
            }
        });
    
    });
    

提交回复
热议问题