make div stick to the top of the screen and stop before hitting the footer

后端 未结 1 846
轻奢々
轻奢々 2020-12-18 14:14

I\'m trying to make a div stick to the header once the user has started scrolling down the page . I found the example How can I make a div stick to the top of the screen on

相关标签:
1条回答
  • 2020-12-18 14:37
    $(window).load($(function()
    {
        var elem = $("#scroller");
        var top = elem.offset().top;
        var maxTop = $("#footer").offset().top - elem.height();
        var scrollHandler = function()
        {
          var scrollTop = $(window).scrollTop();
          if (scrollTop<top) {
            elem.css({position:"relative",top:""})//should be "static" I think
          } else if (scrollTop>maxTop) {
            elem.css({position:"absolute",top:(maxTop+"px")})
          } else {
            elem.css({position:"fixed",top:"0px"})
          }
        }
        $(window).scroll(scrollHandler);scrollHandler()
    
    }));
    

    fiddle: http://fiddle.jshell.net/3ATzd/2/show/ Only think is it doesn't like the margin-top on #scroller. I also removed the need for the scroller-anchor element, so you can remove this.

    0 讨论(0)
提交回复
热议问题