How to simulate touch scrolling with mouse grabbing and dragging?
P粉071626364
P粉071626364 2023-08-26 13:40:28
0
1
449
<p>Here's a minimal example of what I'm trying to do: </p> <p><br /></p> <pre class="brush:html;toolbar:false;"><!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <style> #box { background-color: red; width: 200px; height: 250px; overflow-x: hidden; overflow-y: scroll; cursor: grab; } #box div { background-color: blue; margin: 30px; width: 100px; height: 100px; } </style> </head> <body> <div id="box"> <div></div> <div></div> <div></div> <div></div> <div></div> </div> </body> </html></pre> <p><br /></p> <p>If you're on a mobile device, you can scroll through <code>#box</code> by touching and dragging up or down. However, if you are using a desktop browser, you must use scroll bars or your mouse wheel. </p> <p>How do I enable scrolling by grabbing (i.e. holding down the left mouse button) and then dragging up or down (i.e. moving the mouse)? Can I solve this problem using just CSS? </p>
P粉071626364
P粉071626364

reply all(1)
P粉714780768

This problem cannot be solved using CSS alone, but it can be solved using javascript. I made an implementation for you that works both horizontally and vertically. You can also change the scroll speed.

const box = document.getElementById('box');

let isDown = false;
let startX;
let startY;
let scrollLeft;
let scrollTop;

box.addEventListener('mousedown', (e) => {
  isDown = true;
  startX = e.pageX - box.offsetLeft;
  startY = e.pageY - box.offsetTop;
  scrollLeft = box.scrollLeft;
  scrollTop = box.scrollTop;
  box.style.cursor = 'grabbing';
});

box.addEventListener('mouseleave', () => {
  isDown = false;
  box.style.cursor = 'grab';
});

box.addEventListener('mouseup', () => {
  isDown = false;
  box.style.cursor = 'grab';
});

document.addEventListener('mousemove', (e) => {
  if (!isDown) return;
  e.preventDefault();
  const x = e.pageX - box.offsetLeft;
  const y = e.pageY - box.offsetTop;
  const walkX = (x - startX) * 1; // Change this number to adjust the scroll speed
  const walkY = (y - startY) * 1; // Change this number to adjust the scroll speed
  box.scrollLeft = scrollLeft - walkX;
  box.scrollTop = scrollTop - walkY;
});
#box {
  background-color: red;
  width: 200px;
  height: 250px;
  overflow-x: hidden;
  overflow-y: scroll;
}
#box div {
  background-color: blue;
  margin: 30px;
  width: 100px;
  height: 100px;
}
<div id="box">
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
</div>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template