javascript - 点击事件函数在整个文档上触发
问题描述
我试图关闭一个元素,只有当它在点击时打开但每次点击关闭功能(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
}
}
解决方案
那是因为孩子总是会从父母那里得到点击事件:它被称为事件冒泡,你可以找到几种在线停止它的方法。
你可以做些什么来防止它:
<fs-modal *ngIf="opened" (click)="$event.stopPropagation()" ... >
推荐阅读
- c# - 从 DataGridView 到 DataTable 的转换
- python - 需要使用scrapy提取子页面的内容
- linux - 如何处理引号,反引号特殊字符以在远程服务器中运行 linux bash shell 命令
- android - 禁用“连接到开放网络”
- javascript - 为什么我的 HTML 和 JavaScript 不能在我的 iPad 上运行,但在我的 PC 上运行?
- c - 我无法在主函数中检索更新的值
- node.js - 如何在 netlify-lambda 中访问 gatsby 环境变量
- php - Laravel 通知或可邮寄的朋友请求/接受
- wordpress - 如何将 wordpress/woocommerce 网站移动到新主机和新域?
- hbase - 带有 JMX 导出器 BindException 的 HBase