ng-zorro 弹窗可以拖动

  1. import { Directive, ElementRef, Renderer2, AfterViewInit } from '@angular/core';
  2. @Directive({
  3. selector: '[DragModal]'
  4. })
  5. export class DragModalDirective implements AfterViewInit {
  6. private canMove: boolean = false;
  7. private modalX: number = 0;
  8. private modalY: number = 0;
  9. private distX: number = 0;
  10. private distY: number = 0;
  11. constructor(private elementRef: ElementRef, private render: Renderer2) {
  12. }
  13. target: any = null;
  14. ngAfterViewInit() {
  15. var that: any = this;
  16. that.target = document.getElementsByClassName('dg_class');
  17. let modalElement = that.getModalElement();
  18. let modalTitleElement = that.getModalTitleElment();
  19. that.render.listen(modalTitleElement, 'mousedown', function (event: any) {
  20. that.modalX = modalElement.offsetLeft;
  21. that.modalY = modalElement.offsetTop;
  22. that.distX = event.clientX - modalElement.offsetLeft;
  23. that.distY = event.clientY - modalElement.offsetTop;
  24. that.render.setStyle(modalElement, "position", "absolute");
  25. that.render.setStyle(modalElement, "top", `${that.modalY}px`);
  26. that.render.setStyle(modalElement, "left", `${that.modalX}px`);
  27. that.canMove = true;
  28. }.bind(that));
  29. that.render.listen(modalTitleElement, 'mouseup', function (event: any) {
  30. that.canMove = false;
  31. }.bind(that));
  32. that.render.listen(that.target[that.target.length - 1], 'mousemove', function (event: any) {
  33. if (that.canMove) {
  34. let moveX = event.clientX - that.distX;
  35. let moveY = event.clientY - that.distY;
  36. const modalWidth = modalElement.offsetWidth;
  37. const modalHeight = modalElement.offsetHeight;
  38. const cw = document.documentElement.clientWidth;
  39. const cy = document.documentElement.clientHeight;
  40. if (moveY < 0) {
  41. moveY = 0;
  42. } else if (moveY > cy - modalHeight) {
  43. moveY = cy - modalHeight;
  44. }
  45. if (moveX < 0) {
  46. moveX = 0;
  47. } else if (moveX > cw - modalWidth) {
  48. moveX = cw - modalWidth;
  49. }
  50. that.render.setStyle(modalElement, "top", `${moveY}px`);
  51. that.render.setStyle(modalElement, "left", `${moveX}px`);
  52. // that.render.setStyle(modalTitleElement, "cursor", `move`);
  53. }
  54. }.bind(that));
  55. }
  56. getModalElement() {
  57. return this.target[this.target.length - 1].querySelector('.ant-modal');
  58. }
  59. getModalTitleElment() {
  60. return this.target[this.target.length - 1].querySelector('.ant-modal-header');
  61. }
  62. }