• html拖动滚动


    <div id="container" class="container">...div>

    元素必须至少有两个 CSS 属性:

    1. .container {
    2. cursor: grab;
    3. overflow: auto;
    4. }

    cursor: grab表示可以单击和拖动元素。


    滚动到给定位置

    只要元素是可滚动的,我们就可以通过设置scrollToporscrollLeft属性将其滚动到给定位置:
    1. const ele = document.getElementById('container');
    2. ele.scrollTop = 100;
    3. ele.scrollLeft = 150;


    拖动滚动

    实现非常简单。通过使用Make a draggable element文章中的类似技术,我们从处理mousedown用户单击元素时发生的事件开始:
    1. let pos = { top: 0, left: 0, x: 0, y: 0 };
    2. const mouseDownHandler = function (e) {
    3. pos = {
    4. // The current scroll
    5. left: ele.scrollLeft,
    6. top: ele.scrollTop,
    7. // Get the current mouse position
    8. x: e.clientX,
    9. y: e.clientY,
    10. };
    11. document.addEventListener('mousemove', mouseMoveHandler);
    12. document.addEventListener('mouseup', mouseUpHandler);
    13. };

    pos存储当前滚动和鼠标位置。当用户移动鼠标时,我们计算它已经移动了多远,然后滚动到元素到相同的位置:

    1. const mouseMoveHandler = function (e) {
    2. // How far the mouse has been moved
    3. const dx = e.clientX - pos.x;
    4. const dy = e.clientY - pos.y;
    5. // Scroll the element
    6. ele.scrollTop = pos.top - dy;
    7. ele.scrollLeft = pos.left - dx;
    8. };

    最后但同样重要的是,我们可以通过在用户开始移动鼠标时设置一些 CSS 属性来改善用户体验:

    1. const mouseDownHandler = function(e) {
    2. // Change the cursor and prevent user from selecting the text
    3. ele.style.cursor = 'grabbing';
    4. ele.style.userSelect = 'none';
    5. ...
    6. };

    释放鼠标时,这些 CSS 属性会被重置:

    1. const mouseUpHandler = function () {
    2. document.removeEventListener('mousemove', mouseMoveHandler);
    3. document.removeEventListener('mouseup', mouseUpHandler);
    4. ele.style.cursor = 'grab';
    5. ele.style.removeProperty('user-select');
    6. };

  • 相关阅读:
    基于go语音开源的跨平台端口扫描工具Naabu
    c++ 学习 之 静态存储区域 和常量字符串的联系
    电脑回收站删除的文件如何找回呢?
    当transcational遇上synchronized
    OceanBase 金融项目优化案例
    【NLP】第15章 从 NLP 到与任务无关的 Transformer 模型
    Android导航抽屉
    tp6 workerman
    QT_day1
    mysql学习(四)
  • 原文地址:https://blog.csdn.net/liuhao9999/article/details/125993637