gpt4 book ai didi

javascript - 如何通过单击对话框外部来关闭对话框?

转载 作者:行者123 更新时间:2023-12-05 05:39:22 25 4
gpt4 key购买 nike

除了单击 Esc 按钮之外,您如何通过单击其外部来关闭 dialog 框?

<!DOCTYPE html>
<html>
<body>

<p>Click the button to show the dialog.</p>

<button onclick="myFunction()">Show dialog</button>

<p><b>Note:</b> Use the "Esc" button to close the modal.</p>
<p><b>Note:</b> The dialog element is only supported in Chrome 37+, Safari 6+ and Opera 24+.</p>

<dialog id="myDialog">This is a dialog window</dialog>

<script>
function myFunction() {
document.getElementById("myDialog").showModal();
}
</script>

</body>
</html>

最佳答案

The showModal() method of the HTMLDialogElement interface displays the dialog as a modal, over the top of any other dialogs that might be present. It displays into the top layer, along with a ::backdrop pseudo-element. Interaction outside the dialog is blocked and the content outside it is rendered inert. MDN documentation

如您所见,在对话框 之外的所有其他 html 节点都将被阻止。但是,我们可以添加一个子节点作为我们内容的包装器,这样我们就可以将我们的内容与外部区域分开。让我们使用 css 从 dialog 中删除额外的填充,并将其添加到模态类中。

const dialog = document.getElementById('myDialog');
const button = document.querySelector('button');

function openDialog() {
dialog.showModal();
}

function closeDialog(event) {
// If the target dialog is
if (!event.target.contains(dialog)) return;
dialog.close();
}

button.addEventListener('click', openDialog);
document.addEventListener('click', closeDialog);
dialog {
padding: 0;
}

.modal {
display: flex;
padding: 1rem;
}

dialog::backdrop {
background-color: rgba(255, 0, 0, 0.25);
}
<p>Click the button to show the dialog.</p>

<button>Show dialog</button>

<p><b>Note:</b> Use the "Esc" button to close the modal.</p>
<p><b>Note:</b> The dialog element is only supported in Chrome 37+, Safari 6+ and Opera 24+.</p>

<dialog id="myDialog">
<div class="modal">
<p>This is a dialog window</p>
</div>
</dialog>

关于javascript - 如何通过单击对话框外部来关闭对话框?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72704941/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com