如何通过鼠标抓取和拖动来模拟触摸式滚动?
P粉071626364
P粉071626364 2023-08-26 13:40:28
[HTML讨论组]
<p>这是我正在尝试做的一个最小示例:</p> <p><br /></p> <pre class="brush:html;toolbar:false;">&lt;!doctype html&gt; &lt;html lang="en"&gt; &lt;head&gt; &lt;meta charset="utf-8"&gt; &lt;meta name="viewport" content="width=device-width, initial-scale=1"&gt; &lt;style&gt; #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; } &lt;/style&gt; &lt;/head&gt; &lt;body&gt; &lt;div id="box"&gt; &lt;div&gt;&lt;/div&gt; &lt;div&gt;&lt;/div&gt; &lt;div&gt;&lt;/div&gt; &lt;div&gt;&lt;/div&gt; &lt;div&gt;&lt;/div&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt;</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>
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号