我正面临问题,即使我滚动一次,它也会自动滚动多次。
这是我的JSFiddle。
所以,我想要的是滚动一次时只滚动一个部分。当我向下滚动一次时,应该看到下一部分。同样,当我向上滚动一次时,应该看到上一节。
我尝试从类似的问题获得帮助,但我没有得到一个。感谢您的帮助。
$(function(){
var lastScrollTop = 0, timer;
$(window).scroll(function(event){
clearTimeout(timer);
var windowH, scrollTop, currentSec = 0, scrollRatio, secOffset, secOffsetTop;
scrollTop = $(this).scrollTop();
windowH = $(window).outerHeight();
if (scrollTop == 0) {
currentSec = 1;
} else {
scrollRatio = scrollTop/windowH;
scrollRatio = Math.round(scrollRatio);
currentSec = scrollRatio + 1;
}
secOffset = $("#sec-"+currentSec).offset();
secOffsetTop = secOffset.top;
console.log("currentSec: "+currentSec);
//Stackoverflow Code
timer = setTimeout(function() {
if (scrollTop > lastScrollTop){
// downscroll code
console.log("DOWN DOWN DOWN!");
//$("#sec-" + currentSec).next("section").animate({scrollTop: 0}, 500);
var targetOffset = $("#sec-" + currentSec).next("section").offset();
$('html,body').animate({scrollTop: targetOffset.top}, 1250);
} else {
// upscroll code
console.log("DOWN DOWN UP!");
//$("#sec-" + currentSec).prev("section").animate({scrollTop: 0}, 500);
var targetOffset = $("#sec-" + currentSec).prev("section").offset();
$('html,body').animate({scrollTop: targetOffset.top});
}
lastScrollTop = scrollTop;
//Stackoverflow Code ENDS
}, 1250);
});
});
* {
box-sizing: border-box;
}
body {
margin: 0;
}
section {
height: 100vh;
color: #fff;
font-size: 60px;
padding: 15px;
}
#sec-1 {
background-color: #0ebeff;
}
#sec-2 {
background-color: #47cf73;
}
#sec-3 {
background-color: #fcd000;
}
#sec-4 {
background-color: #b9f;
}
#sec-5 {
background-color: #ff3c41;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<section class="sec-scroll" id="sec-1">Section 1 </section>
<section class="sec-scroll" id="sec-2">Section 2 </section>
<section class="sec-scroll" id="sec-3">Section 3 </section>
<section class="sec-scroll" id="sec-4">Section 4 </section>
<section class="sec-scroll" id="sec-5">Section 5 </section>