javascript 添加缓动/平滑滚动以使用js单击和拖动

osh3o9ms  于 2023-06-28  发布在  Java
关注(0)|答案(2)|浏览(102)

我发现了一个简单的Codepen,它允许我拖动和滚动图像库。它工作正常,但我需要一种方法来添加“平滑抓取/滚动”到这个功能。基本上,我想在iPhone上模拟滚动。
有人能帮帮我吗。我是一个JavaScript的初学者。下面是代码的链接: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);
});

先谢谢你了。

unguejic

unguejic1#

如果我没理解错的话,你是想模仿在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
});

看看它在这里工作:
https://codepen.io/loxks/details/KKpVvVW

az31mfrm

az31mfrm2#

你可以试试这个https://utsb-fmm.github.io/MobileLikeScroller/
我发现更自然的滚动。

相关问题