如何通过触摸和移动调整 div 块的大小?

How to resize div block with touch and move?

我找到了一个从左到右调整大小的示例:stackblitz。如何修改此示例以从右到左调整大小?

我无法获取el.nativeElement.offsetRight

您可以使用此指令:stackblitz

  @Directive({
  selector: '[resizable]'
})
export class ResizableDirective {
  _host: HTMLElement;
  _startWidth = 0;
  constructor(private elm: ElementRef) { }
  ngOnInit() {
    this._host = this.elm.nativeElement;
  }
  dragStart() {
    const style = window.getComputedStyle(this._host, undefined);
    this._startWidth = style.width ? parseInt(style.width, 10) : 0;
  }
  dragging(diff: number) {
    this._host.style.width = this._startWidth + diff + 'px';
  }
  dragEnd() {
    this._startWidth = 0;
  }
}

@Directive({
  selector: '[grabber]',
})
export class GrabberDirective {

  @HostListener('mousedown', ['$event']) mousedown = (e: MouseEvent) => {
    this._startOffsetX = e.clientX;
    document.addEventListener('mousemove', this._boundDragging);
    document.addEventListener('mouseup', this._boundDragEnd);
    this.resizable.dragStart();
  }

  _startOffsetX = 0;
  readonly _boundDragging = (e) => this._dragging(e);
  readonly _boundDragEnd = (e) => this._dragEnd(e);

  constructor(
    private elm: ElementRef,
    @Host() @SkipSelf() private resizable: ResizableDirective,
    ) { }

  private _dragging(e: MouseEvent) {
    const diff = this._startOffsetX - e.clientX;
    this.resizable.dragging(diff);
  }

  private _dragEnd(e: MouseEvent) {
    this._startOffsetX = 0;
    document.removeEventListener('mousemove', this._boundDragging);
    document.removeEventListener('mouseup', this._boundDragEnd);
    this.resizable.dragEnd();
  }
}

html:

<div class="resizable" style="background-color: rebeccapurple;" resizable>
    <p>Lorem ipsum dolor</p>
        <div class="grabber" grabber></div>
</div>

css:

.resizable {
  min-width: 200px;
  height: 100px;
  float:right;
  position: relative;
}

.grabber {
  cursor: col-resize;
  position: absolute;
  background-color: rgb(190, 177, 144);
  width: 5px;
  height: 100%;
  left: 0;
  top: 0;
}