我们需要创建一个drag and drop
指令。使用drag and drop events
对SVG元素不起作用,因此,我们需要使用标准的mousedown
,mousemove
和mouseup
事件。我在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
}
}