使用 jQuery 在文档上捕获 Esc 键,但不捕获内容

发布于 2024-12-25 13:14:13 字数 230 浏览 7 评论 0原文

想象一下 HTML 表单并加载了 jQuery 库。我希望这样,如果有人当前没有专注于表单字段,并且他们单击 Esc 键,则会弹出一个对话框,询问他们是否要关闭表单窗口(因为表单窗口作为新选项卡打开) 。

如果我尝试在 $(document) 上捕获它,我遇到的问题是字段拾取事件冒泡,因此在字段中按下 Esc 键会导致事件触发。

当没有字段获得焦点时,如何有效(关键字)防止事件冒泡并在按下 Esc 时进行捕获?

Imagine an HTML form and the jQuery library is loaded. I'd like it such that if someone is not currently focused on a form field, and they click the Esc key, a dialog pops up to ask if they want to close the form window (because the form window opened as a new tab).

If I try to capture it on $(document), the trouble I have is with event bubbling where the fields pick this up, so an Esc key press in a field causes the event to fire.

How can I efficiently (key word) prevent the event bubble and capture when Esc is pressed when no fields have the focus?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

心是晴朗的。 2025-01-01 13:14:13

您必须使用 If 语句来检查所有输入是否都没有焦点:

if ($('input').is(":focus")){ ... }

In < a href="http://jsfiddle.net/vEB73/" rel="nofollow">我的示例 我使用 Enter 键来检查焦点。

希望这有帮助。

You'll have to use an If statement to check that none of the inputs have focus:

if ($('input').is(":focus")){ ... }

In my example i use the enter key press to check for focus.

Hope this helps.

贪了杯 2025-01-01 13:14:13

试试这个:

    var cancelClose=false; // This is a global variable

    $(document).ready(function(){
        $('input, textarea,select').each(
                function(){
                    $(this).focus(
                            function(){
                                cancelClose=true;
                            }
                        );
                    $(this).blur(
                            function(){
                                cancelClose=false;
                            }
                        );
                }
        );
    });

然后,在文档按键事件上

说:

  if (cancelClose)
         return false;

try this :

    var cancelClose=false; // This is a global variable

    $(document).ready(function(){
        $('input, textarea,select').each(
                function(){
                    $(this).focus(
                            function(){
                                cancelClose=true;
                            }
                        );
                    $(this).blur(
                            function(){
                                cancelClose=false;
                            }
                        );
                }
        );
    });

and then, on document key down event

say :

  if (cancelClose)
         return false;
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文