【问题标题】:html dialog - how to know if the dialog was closed with escapehtml 对话框 - 如何知道对话框是否已通过转义关闭
【发布时间】:2016-11-17 11:18:25
【问题描述】:

我在html中使用dialog标签,如果输入ESC关闭对话框,我想知道它什么时候关闭。

我说的是 html 对话框,而不是 jquery 的对话框。

【问题讨论】:

    标签: html dialog


    【解决方案1】:

    您可以识别 javascript 中的关键事件。您可以执行以下操作:

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

    KeyCode 27 是转义码。

    【讨论】:

    • 但它会为对话框中的每个转义调用,即使我按下转义键让我们说对话框中的组合框,这并不是我真正想要的
    【解决方案2】:

    您可以使用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>

    【讨论】:

      猜你喜欢
      • 2015-04-17
      • 2023-03-15
      • 2012-01-13
      • 2023-02-16
      • 2017-01-24
      • 2013-07-06
      • 2018-11-10
      • 1970-01-01
      • 2018-06-08
      相关资源
      最近更新 更多