import { Directive, ElementRef, OnInit, HostListener } from '@angular/core'; @Directive({ selector: '[appDrag]' }) export class DragDirective implements OnInit { constructor(public el: ElementRef) { } public isDown = false; public disX; // 記錄鼠標點擊事件的位置 X public disY; // 記錄鼠標點擊事件的位置 Y private totalOffsetX = 0; // 記錄總偏移量 X軸 private totalOffsetY = 0; // 記錄總偏移量 Y軸 // 點擊事件 @HostListener('mousedown', ['$event']) onMousedown(event) { this.isDown = true; this.disX = event.clientX; this.disY = event.clientY; } // 監聽document移動事件事件 @HostListener('document:mousemove', ['$event']) onMousemove(event) { // 判斷該元素是否被點擊了。 if (this.isDown) { this.el.nativeElement.style.left = this.totalOffsetX + event.clientX - this.disX + 'px'; this.el.nativeElement.style.top = this.totalOffsetY + event.clientY - this.disY + 'px'; } } // 監聽document離開事件 @HostListener('document:mouseup', ['$event']) onMouseup(event) { // 只用當元素移動過了,離開函數體纔會觸發。 if (this.isDown) { console.log('fail'); this.totalOffsetX += event.clientX - this.disX; this.totalOffsetY += event.clientY - this.disY; this.isDown = false; } } ngOnInit() { this.el.nativeElement.style.position = 'relative'; } }
首先將指令在Module中註冊,在declarations
數組中添加指令。
而後在要拖拽的組件上,添加指令 appDrag
,便可實現拖拽功能。數組