通过单击外部关闭 html5 对话框

问题描述 投票:0回答:1

我在网页中实现了几个 html5 对话框。我希望用户能够单击对话框外部以将其关闭,而不是用关闭按钮使对话框变得混乱或需要按 {escape} 按键。关于这个问题的许多查询都是针对异国情调的 js 库,但我想使用普通 JS 而不是 jquery。

JS

// HALFHIDE
function openHALFHIDEdialog() {
var dialogHALFHIDEsource_O = document.getElementById("S-HALFHIDE");
dialogHALFHIDEsource_O.showModal();
}

function closeHALFHIDEdialog() {
var dialogHALFHIDEsource_C = document.getElementById("S-HALFHIDE");
dialogHALFHIDEsource_C.close(); }

HTML

<!-- S. HALFHIDE -->
<div class = "generic_dialog_container">
<dialog class = "generic dialog" id = "S-HALFHIDE">

<p>Blah blah blah</p>

</dialog></div>
<!-- END S HALFHIDE -->

我该怎么做?

javascript dialog
1个回答
6
投票

编辑:截至 2024 年 4 月 9 日,

dialog
元素已在 2022 年及以后发布的版本中的所有主要浏览器中得到支持。也就是说,现在使用起来是非常安全的。来源:https://caniuse.com/?search=dialog

您可以运行以下 REPL,其中包含解决方案:https://replit.com/@heyitsmarcus/Dialog#index.html

但是,我确实找到了一个适用于 Stack Overflow 的解决方案:How to close the new html

tag by Click on its ::backdrop

dialog.addEventListener('click', function (event) {
    var rect = dialog.getBoundingClientRect();
    var isInDialog=(rect.top <= event.clientY && event.clientY <= rect.top + rect.height
      && rect.left <= event.clientX && event.clientX <= rect.left + rect.width);
    if (!isInDialog) {
        dialog.close();
    }
});
© www.soinside.com 2019 - 2024. All rights reserved.