How can I make a div stick to the top of the screen once it's been scrolled to?

后端 未结 21 1486
Happy的楠姐
Happy的楠姐 2020-11-22 07:12

I would like to create a div, that is situated beneath a block of content but that once the page has been scrolled enough to contact its top boundary, becomes fixed in place

21条回答
  •  一生所求
    2020-11-22 07:52

    sticky till the footer hits the div:

    function stickyCostSummary() {
        var stickySummary = $('.sticky-cost-summary');
        var scrollCostSummaryDivPosition = $(window).scrollTop();
        var footerHeight = $('#footer').height();
        var documentHeight = $(document).height();
        var costSummaryHeight = stickySummary.height();
        var headerHeight = 83;
        var footerMargin = 10;
        var scrollHeight = 252;
        var footerPosition = $('#footer').offset().top;
    
        if (scrollCostSummaryDivPosition > scrollHeight && scrollCostSummaryDivPosition <= (documentHeight - footerHeight - costSummaryHeight - headerHeight - footerMargin)) {
            stickySummary.removeAttr('style');
            stickySummary.addClass('fixed');
    
        } else if (scrollCostSummaryDivPosition > (documentHeight - footerHeight - costSummaryHeight - headerHeight - footerMargin)) {
            stickySummary.removeClass('fixed');
            stickySummary.css({
              "position" : "absolute",
              "top" : (documentHeight - footerHeight - costSummaryHeight - headerHeight - footerMargin - scrollHeight) + "px"
          });
        } else {
            stickySummary.removeClass('fixed');
            stickySummary.css({
                "position" : "absolute",
                "top" : "0"
            });
        }
    }
    
    $window.scroll(stickyCostSummary);
    

提交回复
热议问题