我正在尝试添加一个功能,我可以将其捕捉到最近的子div。 当我慢慢滚动时,这部分工作。但是当我尝试快速滚动(使用鼠标滚轮)时,滚动动画的行为不正确。我认为childToScrollTop变量未正确清除,但我无法确定如何正确更新它。
你能告诉我我做错了什么吗?
const container = document.querySelector(".container");
for (let i = 0; i < 100; i++) {
const child = document.createElement("div");
child.classList.add("child");
child.appendChild(document.createTextNode(i));
container.appendChild(child);
}
let childToScrollTop = 0;
let timeout;
let scrollInterval;
const WAIT_TIME = 200;
const childHeight = 200;
container.addEventListener("scroll", function(e) {
if (timeout) {
clearTimeout(timeout);
}
timeout = setTimeout(() => {
let scrollTop = container.scrollTop;
let mod = container.scrollTop % childHeight;
let q = container.scrollTop / childHeight;
if (mod !== 0) {
childToScrollTop = Math.round(q) * childHeight;
if (scrollInterval) {
clearInterval(scrollInterval);
}
animateContainer();
}
}, WAIT_TIME);
});
function animateContainer() {
var step = 20;
scrollInterval = setInterval(function() {
const diff = container.scrollTop - childToScrollTop;
if (diff >= -1 * step && diff <= step) {
container.scrollTop = childToScrollTop;
clearInterval(scrollInterval);
}
if (container.scrollTop > childToScrollTop) {
container.scrollTop = container.scrollTop - step;
} else if (container.scrollTop < childToScrollTop) {
container.scrollTop = container.scrollTop + step;
}
}, 15);
}
body {
margin: 0;
padding: 0;
display: flex;
align-items: center;
justify-content: center;
height: 100vh;
}
.container {
overflow: auto;
width: 200px;
height: 200px;
border: 10px solid black;
}
.child {
display: flex;
align-items: center;
justify-content: center;
box-sizing: border-box;
height: 200px;
padding: 15px;
border: 1px solid red;
}
<div class="container"></div>
Gif演示此问题:
面对Chrome上的问题