简体   繁体   中英

Position fixed till before footer

I have the following code:

<html>

<head>
<script src="http://code.jquery.com/jquery.min.js" type="text/javascript"></script>

<script>
$(window).on("scroll",function(e){

var sidepos = parseFloat($('#footer').offset().top - $('#side').outerHeight());

if($(window).scrollTop() > 100 && $('#side').offset().top < sidepos) {
   $('#side').css('position','fixed');
   $('#side').css('top','0');
}

else if($(window).scrollTop() > 100 && $('#side').offset().top >= sidepos) {
     $('#side').css('position','absolute');
     $('#side').css('top','' + sidepos + 'px');
}

else if($(window).scrollTop() < 100) {
  $('#side').css('position','');
  $('#side').css('top','');
}

}); 
</script>
</head>

<body>

<div id="header"></div>
<div id="body">
     <div id="side"></div>
</div>
<div id="footer"></div>

</body>
</html>

I want to keep the #side fixed while scrolling till before the #footer so that it doesn't overlap with it.

Now there are 2 problems:

  1. If you scroll down quickly like pressing 'end' button on keyboard, the function will not execute and the side overlaps with the #footer ignoring the if condition.
  2. After switching to position:absolute can't figure out how to fix again when scrolling up and the #side becomes permanently sticking with the #footer even if you scroll up again.

I created a fiddle for you to test: http://jsfiddle.net/JuD5h/

Here is your updated fiddle: http://jsfiddle.net/JuD5h/4/ .

I made some changes to CSS:

#body {
    height: 3000px;
    position: relative;
}
#side {
    width: 100px;
    height: 350px;
    float: left;
    border: 1px solid #000000;
    position: absolute;
    top: 0;
}

And here is the updated Javascript:

$(function(){ // document ready
    var maxAbsoluteTop = $('#body').outerHeight() - $('#side').outerHeight();
    var minAbsoluteTop = 0;
    $(window).scroll(function(){
      var windowTop = $(window).scrollTop();
      var actualTop = windowTop - 100;
      if ( actualTop <= maxAbsoluteTop && actualTop >= minAbsoluteTop) {
          $('#side').css({ top: windowTop - 100 });
      } else if (actualTop > maxAbsoluteTop){
          $('#side').css({ top: maxAbsoluteTop });
      } else {
          $('#side').css({ top: minAbsoluteTop });
      }
    });
});

Use of position: absolute has made the animation flickery but I hope that is something you can fix using a small delay.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM