Home  >  Q&A  >  body text

How to simulate touch scrolling with mouse grabbing and dragging?

<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粉071626364P粉071626364443 days ago440

reply all(1)I'll reply

  • P粉714780768

    P粉7147807682023-08-27 00:26:34

    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>

    reply
    0
  • Cancelreply