我正在使用最新的 HTML5 对话框元素。我使用
showModal
显示多个对话框。那么当多个对话框元素可见时,如何获取最上面的对话框元素呢?
对话框元素似乎没有内置此功能。我认为唯一的解决方案是手动跟踪打开的对话框。
每当打开对话框时,将其附加到数组中。数组中的最后一项将始终是您的活动(最上面)对话框。
function show(dialog) {
dialog.showModal();
openDialogs.push(dialog);
logTopDialog();
}
function close(dialog) {
const i = openDialogs.indexOf(dialog);
if (i !== -1) {
openDialogs.splice(i, 1);
}
logTopDialog();
}
function logTopDialog() {
console.log(`Top dialog = ${openDialogs.at(-1)?.id}`);
}
const openDialogs = [];
btn1.addEventListener('click', e => show(dialog1));
btn2.addEventListener('click', e => show(dialog2));
dialog1.addEventListener('close', _ => close(dialog1));
dialog2.addEventListener('close', e => close(dialog2));
<dialog id="dialog2">
<form method="dialog">
<p>Second dialog!</p>
<button>Close</button>
</form>
</dialog>
<dialog id="dialog1">
<form method="dialog">
<p>This is the first dialog here.</p>
<button id="btn2" type="button">Open Dialog 2</button>
<button>Close</button>
</form>
</dialog>
<button id="btn1">Open Dialog 1</button>
/**
* Get the top dialog of the stack when there are nested dialogs
* @returns
*/
function getTopDialog()
{
/* Get open dialogs on page, by definition they should be nested because
you should only open a child dialog if a dialog is already open, no
siblings or cousins */
const dialogs = document.querySelectorAll("dialog[open]");
if(dialogs == null || dialogs.length == 0)
{
return null;
}
// Create return field
let topDialog = null;
// Loop over open dialogs
dialogs.forEach(dialog => {
const childDialog = dialog.querySelector("dialog[open]");
if(childDialog == null)
{
topDialog = dialog;
}
});
return topDialog;
}