使用鼠标向下 HostListener 移动元素(拖放)



我们需要创建一个drag and drop指令。使用drag and drop events对SVG元素不起作用,因此,我们需要使用标准的mousedownmousemovemouseup事件。我在JavaScript中看到了一些示例,但是不知何故,我没有与Angular一起使用。

mousemove无法选择可拖动元件。

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

我创建了一个stackblitz,这样您就可以看到我所做的。如果我拖动元素并打开控制台,您会发现mousemove事件不会被触发。

我缺少什么?

我支持一种简单的解决方法,因为事件卡住了。

显然,第一个目标是停止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
  }
}