我希望使用jquery代码在页面上使用动画来滚动部分。 我已经编写了一个代码来查找每个部分的顶部和底部,并通过它来获取当前部分,并且动画也可以正常工作,但是滚动时有些毛刺,因为它有点不稳定,并且侧面滚动完全卡住了,动画仍然可以正常工作不需要。我为此添加了一个代码笔链接,请为我提供帮助。我将解释一些代码,因为我已经使用对象存储了每个部分的顶部和底部,并使用找到的这个数组将它们压入了一个数组中当前页面的当前部分,如果下一部分的顶部小于窗口底部,则向下滚动,然后进行滚动动画处理,类似地,向上滚动时,找到上一部分底部并减去窗口高度,然后将动画滚动到该顶部。您。请找到codepen链接。 “ https://codepen.io/anon/pen/jQazdo?editors=1010”
$(document).ready(function() {
(function() {
var sectionData = [];
var lastScrollTop = 0;
var currentSection = 0;
getElementPosition();
console.log(sectionData);
$(window).scroll(function(event) {
var st = $(this).scrollTop();
var windowTopPos = $(window).scrollTop();
var windowBottomPos = $(window).scrollTop() + $(window).height();
if (st > lastScrollTop) {
// downscroll code
console.log("down");
getPresentSection(windowTopPos);
if (currentSection < sectionData.length - 1) {
console.log('top-current', currentSection);
if (sectionData[currentSection + 1].top <= windowBottomPos) {
$('html, body').animate({
scrollTop: sectionData[currentSection + 1].top + 10
}, 500);
// st = 0;
}
}
} else {
// upscroll code
console.log("up");
getPresentSection(windowTopPos);
if (currentSection > -1) {
if (sectionData[currentSection].bottom >= windowTopPos) {
$('html, body').animate({
scrollTop: sectionData[currentSection].bottom - $(window).height()
}, 500);
}
}
// console.log(currentSection);
}
lastScrollTop = st;
$(window).bind("mousewheel", function() {
$("html, body").stop();
});
});
function getPresentSection(st) {
for (var i = 0; i < sectionData.length; i++) {
if (sectionData[i].top <= st && st <= sectionData[i].bottom) {
currentSection = i;
return false;
}
}
}
function getElementPosition() {
$('.section-to-scroll').each(function() {
var position = {
top: $(this).offset().top,
bottom: $(this).offset().top + $(this).outerHeight(true)
}
sectionData.push(position);
});
}
})();
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<style>
.section-to-scroll:nth-child(odd) {
background: rgb(118, 118, 194);
height: 160vh;
}
.section-to-scroll:nth-child(even) {
background: rgb(78, 177, 152);
height: 90vh;
}
.section-to-scroll {
width: 100%;
display: block;
}
body {
border: 0;
margin: 0;
padding: 0;
box-sizing: border-box;
}
</style>
</head>
<body>
<div class="section-to-scroll"></div>
<div class="section-to-scroll"></div>
<div class="section-to-scroll"></div>
<div class="section-to-scroll"></div>
<div class="section-to-scroll"></div>
</body>
<script src="script.js"></script>
</html>