css 如何通过鼠标抓取和拖动来实现触摸式滚动?

ogsagwnx  于 2023-04-23  发布在  其他
关注(0)|答案(1)|浏览(269)

下面是一个我正在尝试做的最小示例:

<!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>

如果你在移动的上,你可以通过触摸和上下拖动来滚动浏览#box。但是,如果你在桌面浏览器上,那么你必须使用滚动条或鼠标滚轮。
如何通过抓取(即按住鼠标左键)然后向上或向下拖动(即移动鼠标)来启用滚动?我可以只用CSS解决吗?

eivnm1vs

eivnm1vs1#

这不能用CSS解决,但它可以使用JavaScript解决。我为你做了一个实现,它可以在水平和垂直方向上工作。它也可以改变滚动速度。

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>

相关问题