https://stackblitz.com/edit/stackblitz-starters-ce1irg?file=src%2Fmain.ts
mouseDown: any = false
centiesX: any
centiesY: any
active: any = {
node: undefined
}
@HostListener('mousedown', ['$event'])
mousedown(e: any) {
this.mouseDown = true
this.active.node = document.getElementsByClassName('n-1234567')[0]
this.active.node.style['position'] = 'absolute'
this.centiesX = e.clientX - +this.active.node?.style.left.split('px')[0]
this.centiesY = e.clientY - +this.active.node?.style.top.split('px')[0]
}
@HostListener('mousemove', ['$event'])
mousemove(e: any) {
if (this.mouseDown) {
this.active.node.style.top = e.pageY - this.centiesY + 'px'
this.active.node.style.left = e.pageX - this.centiesX + 'px'
// if (typeof +this.active.name === 'number' && this.active.name != false) {}
}
}
@HostListener('mouseup', ['$event'])
mouseUp(e: any) {
this.active.node.style['position'] = 'absolute'
this.mouseDown = false
}
//HTML
<div class="n-1234567"></div>
应该只是一个可拖动的方块。如果您快速来回移动,光标就会失去对元素的触摸。我不明白为什么。
谢谢。
问题出在
mousemove
部分。你写的: @HostListener('mousemove', ['$event'])
- 这很好,但是 mousemove 设置为组件 self (所以你的块)。如果光标位于块之外(快速移动),也使用“window:mousemove”和函数句柄:
@HostListener('window:mousemove', ['$event'])
mousemove(e: any) {
if (this.mouseDown) {
this.active.node.style.top = e.pageY - this.centiesY + 'px';
this.active.node.style.left = e.pageX - this.centiesX + 'px';
}
}