如何透過滑鼠抓取和拖曳來模擬觸控式滾動?
P粉071626364
P粉071626364 2023-08-26 13:40:28
0
1
466
<p>這是我正在嘗試做的一個最小範例:</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>如果您使用行動設備,則可以透過觸摸並向上或向下拖曳來捲動 <code>#box</code>。但是,如果您使用的是桌面瀏覽器,則必須使用滾動條或滑鼠滾輪。 </p> <p>如何透過抓取(即按住滑鼠左鍵)然後向上或向下拖曳(即移動滑鼠)來啟用捲動?我可以只用 CSS 解決這個問題嗎? </p>
P粉071626364
P粉071626364

全部回覆(1)
P粉714780768

僅使用 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>
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板