首页 > 解决方案 > 点击事件函数在整个文档上触发

问题描述

我试图关闭一个元素,只有当它在点击时打开但每次点击关闭功能(ClickedOut(event))在弹出窗口打开一次后触发,即使元素已经关闭。

单击弹出窗口将打开的任何框,然后单击弹出元素关闭的任何位置,而目标是一旦单击框打开弹出窗口,则仅在单击弹出元素外部时才应关闭弹出元素。

https://stackblitz.com/edit/angular-7edvms?file=src/app/app.component.ts

<div (click)="ClickedOut($event)">

<div class="box1" (mouseenter)="addClickEvent($event)" 
(mouseleave)="addClickEvent($event)" (click)="addClickEvent($event)">
 On click
</div>

<div class="box2" (mouseenter)="addClickEvent($event)" 
(mouseleave)="addClickEvent($event)" (click)="addClickEvent($event)">
 On click
</div>


<fs-modal *ngIf="opened" [ngStyle]="modalStyleClikedFlag ? modelClickedStyle 
:modelStyle" (mouseleave)="onPopEvent($event)">
</fs-modal>

</div>

TS文件

export class AppComponent {
  modelStyle: any = {
    display: 'none'
  };
  modelClickedStyle: any = {
    display: 'none'
  };

  modalStyleClikedFlag;
  opened;

addClickEvent(e) {
    let x = e.currentTarget.getBoundingClientRect();
 if (e.type === 'click') {
    this.modalStyleClikedFlag = true;
    this.modelClickedStyle = {
    top: 0 + 'px',
    left: 0 + 'px',
    height: 900 + 'px',
    width: 90 + '%',
    display: 'block'
   };
    this.opened = false;
   }
else if (e.type === 'mouseenter') {
    this.opened = true;
    this.modalStyleClikedFlag = false;
    if(((window.innerWidth || document.documentElement.clientWidth) - 
    x.right) >200 ){
    this.modelStyle = {
            top: 0 + 'px',
            left: x.right + 'px',
            height: screen.height + 'px',
            width: 65 +'%',
            display: 'flex'
            };
            }else{
            this.modelStyle = {
            top: 0 + 'px',
            right : ((window.innerWidth||document.documentElement.clientWidth)
           - x.left)
             + 'px',
            height: screen.height + 'px',
            width: 65 +'%',
            display: 'flex'
            };

        }
}
else if (e.type === 'mouseleave' && e.clientX < x.right) {
  this.modelStyle = {
    display: 'none'
  };
}
}

onPopEvent() {
  this.modelStyle = {
   display: 'none'
 };
}

ClickedOut(event): void {
  event.preventDefault();
  this.opened = !this.opened
  }

 }

标签: javascriptangulardomdom-events

解决方案


那是因为孩子总是会从父母那里得到点击事件:它被称为事件冒泡,你可以找到几种在线停止它的方法。

你可以做些什么来防止它:

<fs-modal *ngIf="opened" (click)="$event.stopPropagation()" ... >

推荐阅读