CSS 100VH滚动在第三部分后停止



我正在尝试按每个部分滚动,它在工作,但它不会滚动到最后一部分,只是在第三部分停止,之后不会向下移动。

我在做什么错?

    <div class="body" data-spy="scroll" data-target=".navbar-fixed-top">
      <section id="red" class="bc1">
      </section>
      <section id="blue" class="bc2">
      </section>
      <section id="green" class="bc3">
      </section>
      <section id="blue" class="bc4">
      </section>
    </div>

     <script>
    var $pages = $('section'), tot = $pages.length, c = 0, pagePos = 0, down = 0, listen = true;
    $('.body').on('DOMMouseScroll mousewheel', function(e) {
        e.preventDefault();
        if (!listen)
            return;
        listen = false;
        down = e.originalEvent.detail > 0 || e.originalEvent.wheelDelta < 0;
        c = Math.min(Math.max(0, down ? ++c : --c), tot - 1);
        pagePos = $pages.eq(c).offset().top;
        $(this).stop().animate({
            scrollTop : pagePos
        }, 850, function() {
            listen = true;
        });
    });
</script>

问题是偏移量测量元素与身体顶部的距离。但是,一旦滚动滚动,偏移量是不同的,因为元素已经靠近上一张滚动。

因此,要考虑到这一点,您需要添加.body元素的scrollTop()

更新的代码

var $pages = $('section'),
  tot = $pages.length,
  c = 0,
  pagePos = 0,
  down = 0,
  listen = true,
  body = $('.body');
body.on('DOMMouseScroll mousewheel', function(e) {
  e.preventDefault();
  if (!listen)
    return;
  listen = false;
  down = e.originalEvent.detail > 0 || e.originalEvent.wheelDelta < 0;
  c = Math.min(Math.max(0, down ? ++c : --c), tot - 1);
  pagePos = $pages.eq(c).offset().top + body.scrollTop();
  $(this).stop().animate({
    scrollTop: pagePos
  }, 850, function() {
    listen = true;
  });
});
html,
body {
  margin: 0;
  padding: 0;
  width: 100%;
  height: 100%;
}
.bc1,
.bc2,
.bc3,
.bc4 {
  height: 100vh;
}
#red {
  background: red;
}
#blue {
  background: blue;
}
#green {
  background: green;
}
.body {
  height: 100vh;
  overflow: hidden;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="body" data-spy="scroll" data-target=".navbar-fixed-top">
  <section id="red" class="bc1"></section>
  <section id="blue" class="bc2"></section>
  <section id="green" class="bc3"></section>
  <section id="blue" class="bc4"></section>
</div>

最新更新