我发现了一个简单的Codepen,它使我可以拖动和滚动带有图像的画廊。它工作正常,但是我需要一种向此功能添加“平滑抓取/滚动”的方法。基本上,我想在iPhone上模拟滚动条。
有人可以帮我吗。我是Java语言的初学者。这是代码的链接:Horizontal Click and Drag Scrolling with JS
const slider = document.querySelector('.items');
let isDown = false;
let startX;
let scrollLeft;
slider.addEventListener('mousedown', (e) => {
isDown = true;
slider.classList.add('active');
startX = e.pageX - slider.offsetLeft;
scrollLeft = slider.scrollLeft;
});
slider.addEventListener('mouseleave', () => {
isDown = false;
slider.classList.remove('active');
});
slider.addEventListener('mouseup', () => {
isDown = false;
slider.classList.remove('active');
});
slider.addEventListener('mousemove', (e) => {
if(!isDown) return;
e.preventDefault();
const x = e.pageX - slider.offsetLeft;
const walk = (x - startX) * 3; //scroll-fast
slider.scrollLeft = scrollLeft - walk;
console.log(walk);
});
提前感谢。
如果我正确理解了您的问题,您想效仿在iOS上发布滚动项目后,滚动项目减速至停止的方式。
1)首先,我们需要通过将以下两行添加到mousemove
事件侦听器中来跟踪其拖动时的速度:
var velX;
slider.addEventListener('mousemove', (e) => {
if(!isDown) return;
e.preventDefault();
const x = e.pageX - slider.offsetLeft;
const walk = (x - startX) * 3;
// Store the previous scroll position
var prevScrollLeft = slider.scrollLeft;
slider.scrollLeft = scrollLeft - walk;
// Compare change in position to work out drag speed
velX = slider.scrollLeft - prevScrollLeft;
});
2)拖动完成后,我们创建了一个框架循环,该循环继续以拖动速度滚动,使每次迭代的速度减慢直到停止。
slider.addEventListener('mouseup', () => {
isDown = false;
slider.classList.remove('active');
beginMomentumTracking(); // Start a frame loop to continue drag momentum
});
// Momentum
var momentumID;
function beginMomentumTracking(){
cancelMomentumTracking();
momentumID = requestAnimationFrame(momentumLoop);
}
function cancelMomentumTracking(){
cancelAnimationFrame(momentumID);
}
function momentumLoop(){
slider.scrollLeft += velX; // Apply the velocity to the scroll position
velX *= 0.95; // Slow the velocity slightly
if (Math.abs(velX) > 0.5){ // Still moving?
momentumID = requestAnimationFrame(momentumLoop); // Keep looping
}
}
3)当用户开始与滚动项目交互时,最后取消动量循环
slider.addEventListener('mousedown', (e) => {
isDown = true;
slider.classList.add('active');
startX = e.pageX - slider.offsetLeft;
scrollLeft = slider.scrollLeft;
cancelMomentumTracking(); // Stop the drag momentum loop
});
// Listen for mouse wheel events
slider.addEventListener('wheel', (e) => {
cancelMomentumTracking(); // Stop the drag momentum loop
});