我創建了一個名為 Modal 的小型 Angular 組件,將其用作我的應用程式的模態。單擊頁面上的按鈕時模式打開,單擊背景或取消按鈕時應關閉。
現在在單擊頁面上的按鈕時打開(好)并在單擊背景時關閉(好)我的問題是當我單擊內容時正在關閉(壞)。
為了管理模式何時打開或關閉,我在頁面控制器上定義了一個變數,該變數以 false 開始,當單擊按鈕時切換為 true 并顯示模式。單擊背景時,相同的功能將變數切換回 false。
這是我的board-page.component.ts:
export class BoardPageComponent implements OnInit {
constructor() {}
ngOnInit(): void {}
isModalShown: boolean = false;
newTask() {
console.log(`Click Modal!`);
this.isModalShown ? this.isModalShown = false : this.isModalShown = true;
}
}
這是board-page.component.html:
<app-modal *ngIf="isModalShown" (close)="newTask()">
<h1>Modal Content</h1>
</app-modal>
這是modal組件modal.component.ts:
export class ModalComponent implements OnInit {
@Output() close = new EventEmitter();
constructor() {}
ngOnInit(): void {
}
onClose() {
this.close.emit();
}
}
和modal.component.html
<div class="modal-backdrop" (click)="onClose()">
<div class="modal-content" id='modal'>
<ng-content></ng-content>
</div>
</div>
我已將點擊事件放在背景上,但似乎在點擊內容時點擊事件會觸發 z-index 更高。當點擊事件被觸發時,會向父組件中更新 isModalShown 值的函式發出信號。
以及制作背景和內容效果的樣式:
.modal-backdrop {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100vh;
z-index: 20;
background-color: rgba(0, 0, 0, 0.75);
}
.modal-content {
position: fixed;
top: 15vh;
left: 5%;
width: 90%;
background-color: white;
padding: 1rem;
border-radius: 14px;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.25);
z-index: 30;
animation: slide-down 300ms ease-out forwards;
pointer-events: none;
}
@media (min-width: 768px) {
.modal-content {
width: 40rem;
left: calc(50% - 20rem);
}
}
@keyframes slide-down {
from {
opacity: 0;
transform: translateY(-3rem);
}
to {
opacity: 1;
transform: translateY(0);
}
}
我想我應該禁用內容上的點擊事件?我試過這個:
document.getElementById('modal').addEventListener('click', (event) => {
event.preventDefault();
});
但是沒有用。
如果沒有 3rd 方庫,我沒有找到很多執行此模式的示例。
編輯:我也嘗試使用像這篇文章這樣的自定義指令:停止滑鼠事件傳播但沒有用。
uj5u.com熱心網友回復:
你應該做兩件事:
- 您應該防止從內容部分傳播事件,如下所示
<div class="modal-backdrop" (click)="onClose()">
<div class="modal-content" (click)="$event.stopPropagation()" id="modalmodal">
<ng-content></ng-content>
</div>
</div>
- 您應該從樣式中洗掉指標事件:.modal-content 沒有,這就是為什么事件沒有在您的內容部分中注冊,而您只是以這種方式單擊背景 div。
.modal-content {
position: fixed;
top: 15vh;
left: 5%;
width: 90%;
background-color: white;
padding: 1rem;
border-radius: 14px;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.25);
z-index: 30;
animation: slide-down 300ms ease-out forwards;
pointer-events: none; // remove this line
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/433924.html
標籤:javascript html css 有角度的
