首页 > 解决方案 > 停止导航/侧边栏滚动

问题描述

我希望导航栏在接近底部时停止滚动,这样我仍然可以看到页脚。我仍在学习其中的一些东西,我确信有更好的方法来做到这一点,但这就是我现在所拥有的。

$(window).scroll(function() {
  if ($(window).scrollTop() >= 1000) {
    $('#sticky').addClass('sticky');
  }
  else {
    $('#sticky').removeClass('sticky');
  }
});

这是CSS:

.sticky {
   position: fixed;
   top: 0;
   width: 292.5px;
   background-color: #fff;
   box-shadow: 0px 0px 80px 0px rgba(0, 0, 0, 0.15);
   z-index: 9;
   padding-top: 0;
   padding-bottom: 0;
 }

HTML 在此链接中。(抱歉混淆) http://xmjvn.mdnyd.servertrust.com/

标签: navsticky

解决方案


尝试这个:

$(window).scroll(function() {
  const totalHeight = $(document).height();
  const windowHeight = $(window).height();
  const navHeight = $('#nav').height();
  const footerHeight = $('#footer').height();
  
  if (($(window).scrollTop() + navHeight) < (totalHeight - footerHeight)) {
    $('#nav').addClass('sticky');
  } else {
    $('#nav').removeClass('sticky');
  }
});
body {
  margin-top: 100px;
}

#nav {
  height: 100px;
  background: yellow;
  position: absolute;
  left: 0;
  top: 0;
  width: 100%;
}

#nav.sticky {
  position: fixed;
  width: 100%;
}

#footer {
  margin-top: 1500px;
  background: tomato;
  height: 600px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="nav">nav</div>
<div id="footer">footer</div>


推荐阅读