Stop fixed position at certain div or certain position

孤街浪徒 提交于 2019-12-13 03:49:51

问题


I need to stop a div which gets a fixed position on scroll before it touches another element, basically make it go back to absolute position at a certain position, and this should be working at any size of the screen. I have a jsfiddle with code and there are two elements, please see the example and help if you know the answer thanks!

var navTop = $('#nav').offset().top;
var lastMode = "absolute";

$(window).scroll(function(){
var mode;
if ($(this).scrollTop() >= navTop) {
    mode = 'fixed';
} else {
    mode = 'absolute';
}

if(lastMode !== mode) {
    if (mode == 'fixed') {
        $('#nav').css('position', 'fixed');
        $('#nav').css('top', '0');
    } else {
        $('#nav').css('position', 'absolute');
        $('#nav').css('top', navTop);
    }
    lastMode = mode;
}
});

https://jsfiddle.net/Zygimantas10/vro3LLu9/

let me know if this is not clear.


回答1:


Like this ?

var navTop = $('#nav').offset().top;
var navStop = $('#stop').offset().top;
var lastMode = "absolute";

$(window).scroll(function() {
  var mode;
  if ($(this).scrollTop() >= navTop) {
    if ($(this).scrollTop() - navStop + $('#nav').height() > 0)
      mode = 'absolute';
    else
      mode = 'fixed';
  } else {
    mode = 'absolute';
  }

  if (lastMode !== mode) {
    if (mode == 'fixed') {
      $('#nav').css('position', 'fixed');
      $('#nav').css('top', '0');
    } else {
      $('#nav').css('position', 'absolute');
      $('#nav').css('top', navTop);
    }
    lastMode = mode;
  }
});
#nav {
  background: rgba(0, 0, 0, 0.5);
  position: absolute;
  top: 200px;
  width: 100px;
  height: 50px;
}

#stop {
  width: 100%;
  background: blue;
  height: 300px;
  position: absolute;
  top: 900px;
  margin-top: 20px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body style="height:5000px;">
  <div id="nav"></div>
  <div id="stop"></div>
</body>


来源:https://stackoverflow.com/questions/45328251/stop-fixed-position-at-certain-div-or-certain-position

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!