到达顶部时固定部分。上一部分可见时取消固定

时间:2017-12-13 15:56:20

标签: javascript jquery

我试图在向下滚动浏览器顶部时将section粘贴到顶部,但是当用户向上滚动并且之前{{1}时,我想将其解开回到视野中。

我正在检测从顶部到section的距离我想坚持,但是一旦它在顶部,我们如何检测用户向上滚动并且之前的section重新进入视野。< / p>

我的Codepen:https://codepen.io/omarel/pen/LeEjax

section
$(window).on('scroll', function() {
  var scrollTop = $(window).scrollTop();
  sectionone = $('section.one').offset().top;
  sectiontwo = $('section.two').offset().top;
  sectiontwodistance = (sectiontwo - scrollTop);
  sectiononedistance = (sectionone - scrollTop);
  console.log(sectiononedistance);
  if (sectiontwodistance < 1) {
    $('section.two').addClass('fix');
  }
});
html,
body {
  width: 100%;
  height: 100%;
}

section {
  height: 100%;
  border: 5px solid red;
  position: absolute;
  width: 100%;
}

section.one {
  z-index: 1;
  top: 0%;
}

section.two {
  border: 5px solid green;
  z-index: 2;
  top: 100%;
}

section.three {
  z-index: 3;
  top: 200%;
}

section.fix {
  position: fixed;
  top: 0;
}

1 个答案:

答案 0 :(得分:1)

我会将您的jQuery更新为下面的代码段。它检查第一部分的位置与窗口的高度,如果小于或等于它,则删除.fix类。

$(window).on('scroll', function() {
  var scrollTop = $(window).scrollTop();
  sectionone = $('section.one').offset().top;
  sectiontwo = $('section.two').offset().top;
  sectiontwodistance = (sectiontwo - scrollTop);
  sectiononedistance = (sectionone - scrollTop);
  console.log(sectiononedistance);
  if (sectiontwodistance < 1) {
    $('section.two').addClass('fix');
  }

  if (Math.abs(sectiononedistance) <= $(window).height()) {
    $('section.two').removeClass('fix');
  }
});