[JavaScript] 第1358天 请说说写一个拖拽组件的思路及注意事项

145 阅读2分钟

cover.png 实现一个拖拽组件,可以让用户拖拽某个元素到页面的指定区域,具体的思路如下:

  1. 给需要拖拽的元素添加 mousedown 事件,记录鼠标按下时的位置 startXstartY
  2. document 添加 mousemove 事件,计算鼠标在页面上移动的距离 moveXmoveY
  3. mousemove 事件中动态设置需要拖拽的元素的 topleft 样式属性,值为 startX + moveXstartY + moveY
  4. mouseup 事件中移除 mousemove 事件,拖拽结束。
  5. 需要注意的是,拖拽的元素需要有 position: absoluteposition: fixed 样式属性才能被拖拽,同时拖拽过程中需要设置 cursor: move 样式属性,方便用户识别。

另外,还需要考虑以下注意事项:

  • mousemove 事件中,需要判断鼠标是否已经松开,否则会出现拖拽结束后元素仍然被拖拽的情况。
  • 拖拽元素的移动范围需要限制在指定的区域内,避免拖拽出界。
  • 如果页面中有多个可拖拽的元素,需要判断鼠标点击的目标元素是否是可拖拽的元素,避免拖拽其他元素时触发拖拽事件。

核心代码示例:

class Draggable {
  constructor(element) {
    this.element = element;
    this.isDragging = false;
    this.currentX = 0;
    this.currentY = 0;
    this.initialX = 0;
    this.initialY = 0;
    this.xOffset = 0;
    this.yOffset = 0;

    this.element.addEventListener("mousedown", this.handleMouseDown.bind(this));
    this.element.addEventListener("mouseup", this.handleMouseUp.bind(this));
    this.element.addEventListener("mousemove", this.handleMouseMove.bind(this));
  }

  handleMouseDown(event) {
    this.initialX = event.clientX - this.xOffset;
    this.initialY = event.clientY - this.yOffset;
    this.isDragging = true;
  }

  handleMouseUp() {
    this.initialX = this.currentX;
    this.initialY = this.currentY;
    this.isDragging = false;
  }

  handleMouseMove(event) {
    if (this.isDragging) {
      this.currentX = event.clientX - this.initialX;
      this.currentY = event.clientY - this.initialY;

      this.xOffset = this.currentX;
      this.yOffset = this.currentY;

      this.element.style.transform = `translate3d(${this.currentX}px, ${this.currentY}px, 0)`;
    }
  }
}

const draggableElement = document.querySelector(".draggable");
const draggable = new Draggable(draggableElement);

此示例是一个基于鼠标事件的简单的拖拽组件,它会在鼠标按下时开始拖拽,鼠标抬起时结束拖拽,并在鼠标移动时更新元素的位置。需要注意的是,在实际应用中,还需要处理一些特殊情况,例如边界限制、多个拖拽元素等等。

更多题目

juejin.cn/column/7201…