平滑水平滚动到一个部分



我正在建设一个横向网站。每页有几个部分。

我正在尝试创建以下功能:当用户向右滚动时,页面应该滚动到下一个可用的部分。如果用户向左滚动-返回到上一节。我正在使用jQuery可见库来检查哪个部分在视口中可见。

到目前为止,我尝试了不同的方法,但没有一个是正常工作的。

我将感激任何帮助或指导。谢谢你!:)

下面是我的代码:

<div id="main">
<div class="outer-wrapper outer-wrapper__home">
<div class="wrapper">
<div id="firstSection" class="section"></div>
<div id="secondSection" class="section"></div>
<div id="thirdSection" class="section"></div>
</div>
</div>
</div>

JavaScript/jQuery(一个方法)

let lastScroll = 0;
$('#main').on('scroll', function(event) {
let st = $(this).scrollLeft();
// Scrolling forward
if (st > lastScroll && $('.wrapper .section:nth-child(1)').visible(true) ) {
document.getElementById('secondSection').scrollIntoView({
behavior: 'smooth',
});
}
if (st > lastScroll && $('.wrapper .section:nth-child(2)').visible(true) ) {
document.getElementById('thirdSection').scrollIntoView({
behavior: 'smooth',
});
}
// Scrolling back
if (st < lastScroll && $('.wrapper .section:nth-child(2)').visible(true) ) {
document.getElementById('firstSection').scrollIntoView({
behavior: 'smooth',
});
}
if (st < lastScroll && $('.wrapper .section:nth-child(3)').visible(true) ) {
document.getElementById('secondSection').scrollIntoView({
behavior: 'smooth',
});
}
lastScroll = st;
});

JavaScript/jQuery(另一个方法)

window.addEventListener("wheel", function (e) {
// Scrolling forward
if ( e.deltaY > 0 && $('.wrapper .section:nth-child(1)').visible(true) ) {
document.getElementById('secondSection').scrollIntoView({
behavior: 'smooth',
});
}
if ( e.deltaY > 0 && $('.wrapper .section:nth-child(2)').visible(true) ) {
document.getElementById('thirdSection').scrollIntoView({
behavior: 'smooth',
});
}
// Scrolling back
if ( e.deltaY < 0 && $('.wrapper .section:nth-child(2)').visible(true) ) {
document.getElementById('firstSection').scrollIntoView({
behavior: 'smooth',
});
}
if ( e.deltaY > 0 && $('.wrapper .section:nth-child(3)').visible(true) ) {
document.getElementById('secondSection').scrollIntoView({
behavior: 'smooth',
});
} 
});

这可以不使用javascript或jQuery使用scroll-snap-* css属性来完成。下面的示例演示了使用scroll-snap-*.

水平滚动部分。

.wrapper {
display: flex;
overflow-x: scroll;
-ms-scroll-snap-destination: 0 0;
scroll-snap-destination: 0 0;
-ms-scroll-snap-type: x mandatory;
scroll-snap-type: x mandatory
}
.wrapper .section {
height: 100vh;
width: 100vh;
min-width: 100vw;
scroll-snap-align: start;
scroll-snap-stop: always;
}
.wrapper .section:nth-child(1) {
background: red;
}
.wrapper .section:nth-child(2) {
background: lightgreen;
}
.wrapper .section:nth-child(3) {
background: yellow;
}
<html>
<div id="main">
<div class="outer-wrapper outer-wrapper__home">
<div class="wrapper">
<div id="firstSection" class="section"><h1>First Section</h1></div>
<div id="secondSection" class="section"><h1>Second Section</h1></div>
<div id="thirdSection" class="section"><h1>Third Section</h1></div>
</div>
</div>
</div>
</html>