我想把我的网站分成几个屏幕大小的部分,当用户开始滚动时自动滚动到下一个部分。为了实现这一点,我编写了如下代码:
$(window).scroll(function() {
getElementToScroll().scrollIntoView({behavior: "smooth"});
}但是调用scrollIntoView()会导致递归。我怎样才能避免这个问题?也许还有另一种更合适的滚动元素进入视图的方式?
附言:流畅的行为是必要的。
发布于 2019-12-13 20:04:47
您可以使用CSS Scroll Snap来实现此行为。它不需要JavaScript,只需要CSS。在撰写本文时,除了IE和Edge之外,大多数浏览器都有这个接口的full support。
请查看下面的示例以了解它的实际效果。
html,
body,
.container{
width: 100%;
height: 100%;
}
.container {
scroll-snap-type: y mandatory;
overflow-y: scroll;
}
section {
display: flex;
align-items: center;
justify-content: center;
height: 10em;
width: 100%;
scroll-snap-align: start;
scroll-snap-stop: always
}
section:first-of-type {
background: red;
}
section:nth-of-type(2) {
background: orange;
}
section:nth-of-type(3) {
background: yellow;
}
section:nth-of-type(4) {
background: green;
}
section:nth-of-type(5) {
background: blue;
}
section:nth-of-type(6) {
background: purple;
}<article class="container">
<section>First section</section>
<section>Second section</section>
<section>Third section</section>
<section>Fourth section</section>
<section>Fifth section</section>
<section>Sixth section</section>
</article>
https://stackoverflow.com/questions/59321901
复制相似问题