简体   繁体   English

如何让程序等待模态 window 关闭?

[英]How can I make a program wait for a modal window to close?

Essentially, I'm trying to recreate the "alert" and "prompt" functions, but in a single function that uses a modal window. I have it set up so that when one of the function's parameters is set to 1, it adds a text field to the modal window and records that text field's value when it closes.本质上,我正在尝试重新创建“警报”和“提示”函数,但在使用模态 window 的单个 function 中。我将其设置为当函数的一个参数设置为 1 时,它会添加一个文本字段到模式 window 并在关闭时记录该文本字段的值。 I'm having trouble making it so that when the window is opened, the program waits until the window is closed again.我无法做到这一点,因此当 window 打开时,程序会一直等到 window 再次关闭。 How can I do this?我怎样才能做到这一点?

You need to learn how to use async and await with a promise. Basic idea below showing how the promise is used with the event handler to signal it is clicked.您需要了解如何通过 promise 使用异步和等待。下面的基本概念显示了 promise 如何与事件处理程序一起使用以发出单击信号。

 const myAlert = async(message) => { return new Promise((resolve) => { var modal = document.createElement("div"); modal.classList.add("modal"); modal.innerHTML = ` <div class="modal-content"> <span class="close">&times;</span> <p>${message}</p> </div> `; modal.querySelector(".close").addEventListener("click", function() { modal.remove(); resolve(); }); document.body.append(modal); }); } (async function() { console.log('before'); await myAlert('Hello there'); console.log('after'); })();
 .modal { display: block; position: fixed; z-index: 1; left: 0; top: 0; width: 100%; height: 100%; background-color: rgb(0, 0, 0); background-color: rgba(0, 0, 0, 0.4); }.modal-content { background-color: #fefefe; margin: 15% auto; /* 15% from the top and centered */ padding: 20px; border: 1px solid #888; width: 80%; /* Could be more or less, depending on screen size */ }.close { color: #aaa; float: right; font-size: 28px; font-weight: bold; cursor: pointer; }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM