2016-11-17 53 views

回答

0

您可以在JavaScript中識別關鍵事件。您可以執行以下操作:

$(document).keyup(function(e) { 
    if (e.keyCode === 27) { // do something }; 
}); 

KeyCode 27 is escape。

+0

但它會調用該對話框中的每個逃生,即使我按Escape上可以說,一個對話框內的組合框,這是不是真的什麼我想要 – Pachu

0

當對話框的打開屬性使用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>