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

DAG*_*DAG 4 angular-directive angular

我们需要创建一个drag and drop指令。usingdrag and drop events不适用于 SVG 元素,因此,我们需要使用标准mousedown,mousemovemouseup事件。我在 JavaScript 中看到了一些示例,但不知何故我无法将其与 Angular 一起使用。

mousemove只要未选择可拖动元素即可工作。

如何选择元素并用 拖动它HostListener mousemove

我创建了一个StackBlitz,以便您可以看到我所做的事情。如果我拖动元素并打开控制台,您将看到该mousemove事件不会被触发。

我缺少什么?

Rac*_*hen 6

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

显然,我们的首要目标是阻止该事件preventdefault。在你的hostListener,它支持在你的event

event.preventDefault();
Run Code Online (Sandbox Code Playgroud)

另外,更简单的方法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
  }
}
Run Code Online (Sandbox Code Playgroud)