如何拦截jQuery Dialog ESC键事件? [英] How to intercept jQuery Dialog ESC key event?

查看:181
本文介绍了如何拦截jQuery Dialog ESC键事件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个模态jQuery对话框和另一个在对话框后面接受ESC键事件的元素。当jQuery对话框启动时,我不希望传播这个ESC键事件。现在发生的是当我点击ESC时,它将关闭对话框并触发背景元素上的ESC事件处理程序。

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.

如何吃ESC键事件什么时候关闭jQuery对话框?

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

推荐答案

内部jQuery UI对话框的 closeOnEscape 选项是通过将keydown侦听器附加到文档本身来实现的。因此,一旦keydown事件一直冒泡到顶层,对话框就会关闭。

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.

因此,如果你想继续使用转义键来关闭对话框,并且您希望保持转义键不会传播到父节点,您需要自己实现 closeOnEscape 功能以及使用事件对象上的stopPropagation 方法(请参阅有关事件的MDN文章。 stopPropagation )。

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();
    });
}());

这样做是为了监听对话框中发生的所有keydown事件。如果按下的键是转义键,则按正常方式关闭对话框,无论 evt.stopPropagation 调用是否保持keydown不会冒泡到父节点。

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.

我在这里有一个现场示例 - http:// jsfiddle.net/ud9KL/2/

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

这篇关于如何拦截jQuery Dialog ESC键事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆