使用mousedown HostListener移动元素(拖放)

问题描述 投票:2回答:1

我们需要创建一个drag and drop指令。使用drag and drop events不适用于SVG元素,因此,我们需要选择标准的mousedownmousemovemouseup事件。我在JavaScript中看到了一些例子,但不知怎的,我没有让它与Angular一起工作。

没有选择mousemove工作solong可拖动元素。

我如何挑选元素并用HostListener mousemove拖动它?

我创造了一个StackBlitz,所以你可以看到我做了什么。如果我拖动元素并打开控制台,您将看到不会触发mousemove事件。

我错过了什么?

angular angular-directive
1个回答
1
投票

由于事件卡住,我支持一种简单的解决方法。

显然,第一个目标是停止preventdefault事件。在你的hostListener,它支持你的event

event.preventDefault();

此外,它有更简单的方法是return false,它将是中断。

@HostListener('document:mousedown', ['$event'])
onMouseDown(event) {
  // we make sure only draggables on the document elements are selected
  if (event.target.getAttribute('draggable')) {
    console.log('mousedown');

    this.currentX = event.clientX;
    this.currentY = event.clientY;
    this.selectedElement = event.target;
    // ##### add this code.
    event.preventDefault();    // choose one
    // ##### or add this code.
    return false;    // choose one
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.