Switch div from fixed to absolute at bottom of browser

前端 未结 5 1934
梦毁少年i
梦毁少年i 2021-01-18 01:51

Im trying to add a footer at the bottom of this content that doesn\'t overlay the content but moves it up.

The only way I can see it working would be something like,

5条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-18 02:22

    If I understand your question correct, this should do the trick (although it depends very much on JavaScript unfortunately).

    // Fix work column on scroll
    contentStart = $("#content").offset().top ;
    contentSize  = $("#content").height() ;
    
    window.onscroll = function(){   
        if( window.XMLHttpRequest ) {
            var position=window.pageYOffset;
    
            // calculate the position of the footer and the actual seen window            
            var docViewTop = $(window).scrollTop();
            var docViewBottom = docViewTop + $(window).height();
            var elemTop = $("#footer").offset().top;
    
             if ( position > 300 && !(docViewBottom >= elemTop)) {
                 $('#work').css({'position':'fixed', 'top':'0', 'height':'100vh'});
              } else {
                  // if the footer is visible on the screen
                  if(docViewBottom >= elemTop) {
                     $('#work').css({ 'top': 0 - (docViewBottom - elemTop) }); // scroll the #main div relative to the footer       
                  } else {
                      $('#work').css({'position':'relative', 'top': 'auto'}) ;
                  }
             }
    
        }
    }
    

    For further informations about the calculations, perhaps this question on stackoverflow is useful.

    Edit: Andrew Haining posted his answer in between of my answer, perhaps give his link a try and maybe it's a better (more proper) solution. Unfortunately I haven't actualised this page when I was testing your code in JSFiddle and I didn't see his answer.

    If you want to use my script, make sure you can test it with different resolutions. It works just fine for my resolution in JSFiddle, I didn't test any other.

提交回复
热议问题