1. 指令代码
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';
}
}2.使用
首先将指令在module中注册,在declarations数组中添加指令。
然后在要拖拽的组件上,添加指令 appdrag ,即可实现拖拽功能。
以上就是angular6实现拖拽功能指令drag实例详解的详细内容,更多关于angular6拖拽功能指令drag的资料请关注代码网其它相关文章!
发表评论