drag-element.ts 1.62 KB
Newer Older
Chen Jiping's avatar
Chen Jiping committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58
import { EventEmitter } from '@angular/core';

export class DragElement {
  onMove = new EventEmitter();
  canMove = false;
  dragEl = null;
  relX = 0;
  private readonly bindMove: any;
  private readonly maxWidth: any;
  private readonly bindDown: any;
  private readonly bindUp: any;
  constructor(el, maxWidth) {
    this.dragEl = el;
    this.maxWidth = maxWidth;
    this.bindMove = this.move.bind(this);
    this.bindDown = this.down.bind(this);
    this.bindUp = this.up.bind(this);
    this.dragEl.addEventListener('mousedown', this.bindDown, false);
    document.addEventListener('mouseup', this.bindUp, false);
  }
  dispose() {
    this.dragEl.removeEventListener('mousedown', this.bindDown, false);
  }
  down(e) {
    document.addEventListener('mousemove', this.bindMove, false);
    // relX = e.pageX - this.timeLine.offsetWidth || 0;
    // const left = parseInt(el.offsetWidth|| 0)
    const matrix = new DOMMatrix(this.dragEl.style.transform);
    this.relX = e.pageX - matrix.m41 || 0;
    this.canMove = true;
  }
  up(e) {
    this.canMove = false;
    document.removeEventListener('mousemove', this.bindMove, false);
  }
  move(e) {
    if (!this.canMove) {
      return;
    }
    const matrix = new DOMMatrix(this.dragEl.style.transform);
    const w = matrix.m41;
    if (w > this.maxWidth) {
      this.dragEl.style.transform = `translateX(${this.maxWidth}px)`;
      return;
    }
    if (w < 0 ) {
      this.dragEl.style.transform = `translateX(0px)`;
      return;
    }
    // this.dragEl.style.transform = `translateX(${(e.pageX - this.relX)}px)`;
    this.onMove.emit({
      position: e.pageX - this.relX,
    });

  }
}