首页 > 解决方案 > 在 Angular 中拖动时弹出模式会粘在鼠标光标上

问题描述

它有效,但弹出窗口粘在鼠标光标上

这是我正在使用的 Draggable Angular Directive 的代码

import { Observable } from 'rxjs';
import { takeUntil } from 'rxjs/operators';

@Directive({
  selector: '[draggable]',
})

export class DraggableDirective implements AfterViewInit {

  @Input() currentTarget: string;
  @Input() isStandAlone: boolean = true;

  private mouseup = new EventEmitter<MouseEvent>();
  private mousedown = new EventEmitter<MouseEvent>();
  private mousemove = new EventEmitter<MouseEvent>();
  private target: HTMLElement;
  private handle: HTMLElement;

  private mousedrag: Observable<{ top, left }>;

  private active = false;
  private currentX;
  private currentY;
  private initialX;
  private initialY;
  private xOffset = 0;
  private yOffset = 0;
  private drag=true;

  @HostListener('document:mouseup', ['$event'])
  onMouseup(event: MouseEvent) {
    console.log("mouseUp");
    this.active = false;
    this.initialX = this.currentX;
    this.initialY = this.currentY;
    this.target.draggable=false;

    this.mouseup.emit(event);
    // console.log("Target" + this.target.draggable);
    // console.log("Event" + event.target)

  }

  @HostListener('mousedown', ['$event'])
  onMousedown(event: MouseEvent) {
   
this.target.draggable=false;    
    this.mousedown.emit(event);
    //return true;
    // console.log("Target" + this.target.draggable);
    // console.log("Event" + event.target)
  }

  @HostListener('document:mousemove', ['$event'])
  onMousemove(event: MouseEvent) {
    this.mousemove.emit(event);
    this.target.draggable=false;
  }

  constructor(public element: ElementRef) { }

  public ngAfterViewInit(): void {

    if(this.currentTarget){
    const currentElement: HTMLElement = document.querySelector(`#${this.currentTarget}`);
    if (this.isStandAlone) {

      this.target = currentElement.offsetParent.parentElement;
    } 
    else {
      this.target = currentElement.querySelector('.modal-dialog');
      //this.target.draggable = true;
    }

    this.handle = this.target.querySelector('#modalHandle');
    if(this.handle) {
      this.handle.style.cursor = 'pointer';
    }

    this.target.style.position = 'relative';
    this.mousedrag = this.mousedown.map(event => {
      this.initialX = event.clientX - this.xOffset;
      this.initialY = event.clientY - this.yOffset;
      if (event.target === this.handle) {
        this.active = true; 
        //event.target.draggable = false;
        console.log(event.type);
        console.log("Target" + this.target.draggable);
        console.log("Event" + event.draggable)

            

     }  

  

     else
     

      return {
        top: this.initialY,
        left: this.initialX,
      };
    })
      .flatMap(
        imageOffset => this.mousemove.map(
          pos => ({
            top: pos.clientY,
            left: pos.clientX,
          }))
          .pipe(takeUntil(this.mouseup)));

    this.mousedrag.subscribe({
      next: pos => {
        if (this.active) {

          this.currentX = pos.left - this.initialX;
          this.currentY = pos.top - this.initialY;
          this.xOffset = this.currentX;
          this.yOffset = this.currentY;

          this.target.style.top = this.currentY + 'px';
          this.target.style.left = this.currentX + 'px';
          
          this.target.draggable=false;

        
        }
        console.log("Target" + this.target.draggable);
        return false;
        
      }
    });
  }


  }

  
} 

这是 HTML Popup Modal 的代码,它在拖动时会粘在鼠标光标上

<section class="custom-modal--wrap" *ngIf="showModal">
   <div class="modal fade addeditCovenantRule"  [draggable] currentTarget="modal-dialog2" [isStandAlone]=false  id="modal-dialog2"   data-backdrop="static" tabindex="-1" role="dialog" aria-labelledby="modalIdLabel" >

        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div id="modalHandle" class="modal-header">

                    Edit Asset Class
                    <button type="button" id="closeTestBtn" class="close" aria-label="Close popup" data-dismiss="modal"
                        (click)="clearOptionsEditAsset();">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <form [formGroup]="editAssetForm">

                    <div class="modal-body">

                        <div class="col-md-12 mtb10">
                            <div class="dropdown">
                                <label for="fa" class="body-title">Asset:</label>
                                <button id="fa" class="input-group ruleoptions border-left border-top border-bottom "
                                    data-display="static" style=" cursor: pointer;" type="button"
                                    style=" background-image: url('assets/images/arrow.svg');"
                                    data-toggle="dropdown"><span id="fa">{{selectedAsset}}</span>


                                </button>
                                <ul class="dropdown-menu asset-dropdown" role="menu">
                                    <li *ngFor="let asset of assets">
                                        <a id="" class="dropdown-item" role="menuitem" (click)="selectAsset(asset)"
                                            href="javascript:void(0)">{{asset.assetName}}</a>
                                    </li>
                                </ul>
                            </div>
                        </div>
                        <div class="col-md-12 mtb10">
                            <div class="dropdown">
                                <label for="cus" class="body-title">Asset Class:</label>
                                <button id="cus" class="input-group ruleoptions border-left border-top border-bottom "
                                    data-display="static" style=" cursor: pointer;" type="button"
                                    style=" background-image: url('assets/images/arrow.svg');"
                                    data-toggle="dropdown"><span id="cus">{{selectedAssetClass}}</span>


                                </button>
                                <ul class="dropdown-menu assetClass-dropdown" role="menu">
                                    <li *ngFor="let assetClass of assetClasses">
                                        <a id="{{assetClass.criteriaID}}" class="dropdown-item" role="menuitem"
                                            href="javascript:void(0)"
                                            (click)="selectAssetClass(assetClass)">{{assetClass.criteriaName}}</a>
                                    </li>
                                </ul>
                            </div>
                        </div>
                        <div class="datepicker-field col-md-6 form-group portfolio_datepicker__field">
                            <label for="thruDate" class="thruDate"> Thru Date:</label>
                            <mat-form-field class="date-field">
                                <input class="form-control" id="thruDate" name="thruDate" matInput
                                    [matDatepicker]="start" formControlName="thruDate" [min]="currentDate"
                                    (dateInput)="thruDateEvent()">
                                <mat-datepicker-toggle matSuffix [for]="start"></mat-datepicker-toggle>
                                <mat-datepicker #start></mat-datepicker>
                            </mat-form-field>
                        </div>
                        <div class="col-md-12 mtb10">
                            <div class="notes-label">Reason for change:</div>
                            <textarea (keypress)="noteEvent($event)" formControlName="note" class="notes-field"
                                maxlength="100">{{editAssetForm.controls['note'].value}}</textarea>
                        </div>
                        <div style="color: red; padding-left: 10px;" *ngIf="thrudateError?.length">
                            <span>{{thrudateError}}</span></div>
                        <div style="color: red; padding-left: 10px;" *ngIf="errormsg?.length"><span>{{errormsg}}</span>
                        </div>
                        <div style="color: red; padding-left: 10px;" *ngIf="assetErrormsg?.length">
                            <span>{{assetErrormsg}}</span></div>
                    </div>
                    <div class="modal-footer">
                        <div class="footer-btn--wrap">
                            <input type="button" class="cancel-btn btn btn-secondary" data-dismiss="modal"
                                (click)="clearOptionsEditAsset();" value="Cancel" />
                            <button type="button" id="editassetbtn" (click)="save();" class="add-btn btn btn-primary">
                                Save </button>
                        </div>
                    </div>
                </form>
            </div>
        </div>
    </div>

</section>

弹出窗口是 html 。当我们尝试拖动弹出窗口时,它会拖动,但它会粘在鼠标光标上。当我们再次单击它时,它就会被释放。

标签: javascripthtmlangulardraggabledirective

解决方案


推荐阅读