【发布时间】:2016-11-17 11:18:25
【问题描述】:
我在html中使用dialog标签,如果输入ESC关闭对话框,我想知道它什么时候关闭。
我说的是 html 对话框,而不是 jquery 的对话框。
【问题讨论】:
我在html中使用dialog标签,如果输入ESC关闭对话框,我想知道它什么时候关闭。
我说的是 html 对话框,而不是 jquery 的对话框。
【问题讨论】:
您可以识别 javascript 中的关键事件。您可以执行以下操作:
$(document).keyup(function(e) {
if (e.keyCode === 27) { // do something };
});
KeyCode 27 是转义码。
【讨论】:
您可以使用MutationObserver 在对话框的打开属性更改时触发事件。代码来源于Mats 回复firing event on DOM attribute change
window.MutationObserver = window.MutationObserver || window.WebKitMutationObserver || window.MozMutationObserver;
var dialog = document.querySelector('dialog');
var btn = document.querySelector('#open-dialog');
var observer = new MutationObserver(onDialogMutation);
btn.addEventListener('click', function() {
dialog.showModal();
observer.observe(dialog, {
attributes: true
});
});
function onDialogMutation(mutation) {
observer.disconnect();
console.log('Dialog Closed');
}
<!doctype html>
<html lang="en">
<head>
<title>Dialog MutationObserver</title>
</head>
<body>
<dialog>My Dialog</dialog>
<input id="open-dialog" type="button" value="open dialog" />
</body>
</html>
【讨论】: