如何检测“ <section>”的20%是否可见?

时间:2019-03-18 14:13:53

标签: javascript html css

如您所见,我有两个部分占据整个页面。 我想在滚动时检测第二部分是否可见20%,如果这样,则强制第二部分平滑滚动并锁定该部分,以便占用整个空间。如果添加更多内容,则与其他部分相同。

(我可以做的光滑的部分)。

任何人都知道我该怎么做?

* {
    margin: 0;
    padding: 0;
}

#s1 {
  height: 100vh;
  background: red;
}

#s2 {
  height: 100vh;
  background: blue;
}
<section id="s1"></section>
<section id="s2"></section>

1 个答案:

答案 0 :(得分:0)

var section = document.querySelector('section'),
    sectionHeight = section.offsetHeight,
    lastScrollTop = 0;
document.addEventListener("scroll", function() {
    var scrollY = window.pageYOffset || document.documentElement.scrollTop;

    if (scrollY > lastScrollTop) { //on scroll down
        if (scrollY >= sectionHeight * 0.2 && scrollY < sectionHeight) { //if 20% of section2 is visible
            window.scrollTo(0, sectionHeight * 1); //scroll to section2
        } else if (scrollY >= sectionHeight * 1.2 && scrollY < 2 * sectionHeight) { //if 20% of section3 is visible
            window.scrollTo(0, sectionHeight * 2); //scroll to section3
        } else if (scrollY >= sectionHeight * 2.2) { //if 20% of section4 is visible
            window.scrollTo(0, sectionHeight * 3); //scroll to section4
        }
    }
    lastScrollTop = scrollY <= 0 ? 0 : scrollY;
});
* {
    margin: 0;
    padding: 0;
}
html,body{
  scroll-behavior: smooth;
}
section{
  height: 100vh;
}
#s1 {
  background: red;
}
#s2 {
  background: blue;
}
#s3{
  background: yellow;
}
#s4{
  background:purple;
}
<section id="s1"></section>
<section id="s2"></section>
<section id="s3"></section>
<section id="s4"></section>