当前位置: 代码网 > it编程>前端脚本>AngularJs > Angular6实现拖拽功能指令drag实例详解

Angular6实现拖拽功能指令drag实例详解

2024年05月15日 AngularJs 我要评论
1. 指令代码import { directive, elementref, oninit, hostlistener } from '@angular/core';@directive({ sel

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的资料请关注代码网其它相关文章!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com