From 61bb125623bbf5dc90c9a4c9177cffe668e203cf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E8=A7=89?= Date: Thu, 5 Oct 2023 14:03:51 +0800 Subject: [PATCH] =?UTF-8?q?=E6=8C=89=E4=B8=8B=20ESC=20=E5=85=B3=E9=97=AD?= =?UTF-8?q?=E5=BC=B9=E7=AA=97?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- public/weigets.js | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/public/weigets.js b/public/weigets.js index b4263d3..c56cbbd 100644 --- a/public/weigets.js +++ b/public/weigets.js @@ -44,6 +44,7 @@ export function Avatar(options) { export function Dialog(options) { const element = createElement({}, 'div') const content = createElement(options) + element.tabIndex = 0 // 使元素可以获得焦点 element.style.cssText = ` position: fixed; top: 0; @@ -77,6 +78,24 @@ export function Dialog(options) { element.remove() } } + // 按下 ESC 关闭 + element.onkeydown = async event => { + if (event.key === 'Escape') { + await element.animate([{ opacity: 1 }, { opacity: 0 }], { duration: 100 }).finished + element.remove() + } + } + // 显示时自动聚焦 + const observer = new MutationObserver((mutationsList) => { + for (const mutation of mutationsList) { + if (mutation.type === 'childList' && mutation.addedNodes.length > 0) { + element.focus() + return + } + } + }) + // 监听 Dialog 元素的插入 + observer.observe(document.body, { childList: true, subtree: true }) return element }