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

Rod*_*Rod 5 html javascript

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

<!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>
Run Code Online (Sandbox Code Playgroud)

Ant*_*ton 3

HTMLDialogElement 接口的 showModal() 方法将对话框显示为模式,位于可能存在的任何其他对话框之上。它与 ::backdrop 伪元素一起显示在顶层。对话框外部的交互被阻止,并且对话框外部的内容呈现惰性。MDN 文档

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

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);
Run Code Online (Sandbox Code Playgroud)
dialog {
  padding: 0;
}

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

dialog::backdrop {
  background-color: rgba(255, 0, 0, 0.25);
}
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)