How to intercept jQuery Dialog ESC key event?

。_饼干妹妹 提交于 2019-12-23 06:58:52

问题


I have a modal jQuery dialog and another element that takes the ESC key event behind the dialog. When the jQuery Dialog is up, I don't want this ESC key event to propagate. What happens now is that when I click on ESC, it will close the dialog and trigger the ESC event handler on the background element.

How do I eat the ESC key event when a jQuery dialog is dismissed?


回答1:


Internally jQuery UI's dialog's closeOnEscape option is implemented by attaching a keydown listener to the document itself. Therefore, the dialog is closed once the keydown event has bubbled all the way to the top level.

So if you want to keep using the escape key to close the dialog, and you want to keep the escape key from propagating to parent nodes, you'll need to implement the closeOnEscape functionality yourself as well as making use of the stopPropagation method on the event object (see MDN article on event.stopPropagation).

(function() {
  var dialog = $('whatever-selector-you-need')
    .dialog()
    .on('keydown', function(evt) {
        if (evt.keyCode === $.ui.keyCode.ESCAPE) {
            dialog.dialog('close');
        }                
        evt.stopPropagation();
    });
}());

What this does is listen for all keydown events that occur within the dialog. If the key pressed was the escape key you close the dialog as normal, and no matter what the evt.stopPropagation call keeps the keydown from bubbling up to parent nodes.

I have a live example showing this here - http://jsfiddle.net/ud9KL/2/.




回答2:


You need closeOnEscape...

Example code:

$(function() {
$("#popup").dialog({
height: 200,
width: 400,
resizable: false,
autoOpen: true,
modal: true,
closeOnEscape: false
});
});

See it live: http://jsfiddle.net/vutdV/




回答3:


You can use the following

    $(document).keyup(function (e) {
        if (e.keyCode == 27) {

            $('#YourDialogID').dialog('close')  
        }
    });



回答4:


You would need to modify the code for your element behind the dialog to see if the dialog was open AND the escape key was pressed and to ignore that situation.



来源:https://stackoverflow.com/questions/10466726/how-to-intercept-jquery-dialog-esc-key-event

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!