当模态对话框打开时,用户希望使用熟悉的控件将其关闭:按键盘上的 Esc 键、在移动平台上使用返回按钮或手势,或通过辅助技术使用关闭手势。
<dialog> 元素首次推出时,可以通过 Esc 键关闭,但无法通过其他平台控件(例如移动设备上的返回按钮/手势)关闭。随着 <dialog> 元素的 closedby 属性的添加,在模态状态下打开的 <dialog> 元素(即在 JavaScript 中使用 <dialog> 元素的 showModal() 方法以命令式方式打开,或使用 show-modal 调用方命令以声明式方式打开)已应用了响应更多平台特定控件以关闭请求的扩展行为。因此,如果开发者已经在使用 <dialog> 元素,则无需进行任何特定更改。
<!-- MANDATORY: must be opened with either `showModal()` with JavaScript or the `show-modal` command using declarative command invokers in order respond to close requests including platform-specific controls. -->
<dialog aria-labelledby="example">
<h1 id="example">Example</h1>
<p>Modal that can be dismissed with close requests.</p>
</dialog>
在模态状态下打开时,没有 closedby 属性的对话框对关闭请求的响应与将 closedby 属性显式设置为 closerequest 相同。
<!-- This is unnecessary as it is the default behavior for modal dialogs -->
<dialog closedby="closerequest" aria-labelledby="example">
<h1 id="example">Example</h1>
<p>Modal that can be dismissed with close requests.</p>
</dialog>
如果您还希望实现“轻触关闭”行为,则必须将 closedby 设置为 any:
<dialog closedby="any" aria-labelledby="example">
<h1 id="example">Example</h1>
<p>Modal that can be dismissed with close requests and light dismiss.</p>
</dialog>
后备策略
以模态状态打开的 <dialog> 元素已经可以使用 Esc 键关闭,因此无需回退。目前没有很好的方法来实现通过移动设备返回按钮/手势关闭请求,因此更简单的方法是将此功能作为渐进增强功能,尤其是考虑到还有其他包容性方法可以关闭模态对话框。同样,使用 closedby="any" 的 <dialog> 元素的轻触关闭行为可被视为渐进增强。