DOM拖拽移动位置封装

发布时间 2023-08-02 09:44:22作者: SKILL·NULL
 class Drage {
  constructor() {
    this.ref
    this.draggingFlag = false
    this.initX
    this.initY
    this.currentX
    this.currentY
    this.offsetX = 0
    this.offsetY = 0
    this.style = `z-index: 999999;`
  }

  listen(ref, style) {
    this.ref = ref
    if (style) {
      this.style = style
    }

    this.ref && this.ref.setAttribute('draggable', 'true')

    this.ref && this.ref.addEventListener('touchstart', _ => this.onStart(_, this))
    this.ref && this.ref.addEventListener('mousedown', _ => this.onStart(_, this))

    this.ref && this.ref.addEventListener('touchend', _ => this.onEnd(_, this))
    this.ref && this.ref.addEventListener('mouseup', _ => this.onEnd(_, this))
    this.ref && this.ref.addEventListener('mouseout', _ => this.onEnd(_, this))
  }

  onStart(event, _this) {

    if (event.changedTouches && event.changedTouches[0]) {
      _this.initX = event.changedTouches[0].clientX - _this.offsetX
      _this.initY = event.changedTouches[0].clientY - _this.offsetY
    }

    _this.ref && _this.ref.addEventListener('touchmove', _ => _this.onMove(_, _this))
    _this.ref && _this.ref.addEventListener('mousemove', _ => _this.onMove(_, _this))

    _this.draggingFlag = true
  }

  onMove(event, _this) {
    if (_this.draggingFlag) {
      event.preventDefault()
      if (event.changedTouches && event.changedTouches[0]) {
        _this.currentX = event.changedTouches[0].clientX - _this.initX
        _this.currentY = event.changedTouches[0].clientY - _this.initY
        _this.offsetX = _this.currentX
        _this.offsetY = _this.currentY

        if (_this.ref) {
          _this.ref.style = `
            transform: translate(${_this.currentX}px, ${_this.currentY}px);
            ${_this.style}
          `
        }
      }
    }
  }

  onEnd(event, _this) {
    _this.ref && _this.ref.removeEventListener('touchmove', _ => _this.onMove(_, _this))
    _this.ref && _this.ref.removeEventListener('mousemove', _ => _this.onMove(_, _this))
    _this.draggingFlag = false
  }

  removeListen(ref) {
    const _ref = ref ? ref : this.ref
    if (!_ref) return
    _ref.removeEventListener('touchmove', _ => this.onMove(_, this))
    _ref.removeEventListener('mousemove', _ => this.onMove(_, this))
    _ref.removeEventListener('touchstart', _ => this.onStart(_, this))
    _ref.removeEventListener('mousedown', _ => this.onStart(_, this))
    _ref.removeEventListener('touchend', _ => this.onEnd(_, this))
    _ref.removeEventListener('mouseup', _ => this.onEnd(_, this))
    _ref.removeEventListener('mouseout', _ => this.onEnd(_, this))
  }
}

export default new Drage()

初始化拖拽:Drage.listen(this.$refs.dragDom)
删除拖拽:Drage.removeListen()