【问题标题】:Keyboard shortcuts with jQuery使用 jQuery 的键盘快捷键
【发布时间】:2010-10-10 06:22:58
【问题描述】:

如果有人按下字母 g,我如何连接一个事件来触发?

(顺便说一句,所有字母的字符映射在哪里?)

【问题讨论】:

标签: javascript jquery keyboard-shortcuts


【解决方案1】:

自从最初提出这个问题以来,John Resig(jQuery 的主要作者)已经分叉并改进了 js-hotkeys 项目。他的版本在:

http://github.com/jeresig/jquery.hotkeys

【讨论】:

  • 它支持meta 键,js-hotkeys 中不支持的东西 :) 谢谢
  • 他有一个 Nuget 包,所以我选择了这个。
  • 我必须说,它非常适合组合键(尤其是那些特殊的键,如 shift、ctrl、alt、...),但我在基本映射 0-9 和 az 时遇到了问题) .
  • 这个答案确实提供了有用的链接。你也能回答原来的问题吗?例如。 “如果有人按下字母 g,我如何连接一个事件来触发”? jquery.hotkeys 模块有一些文档,如果您已经知道自己在做什么,我敢肯定它很棒......但是对于我们这些试图一起破解某些东西的人来说,原始问题的答案会很棒。
  • 如何防止默认冒泡到浏览器?从我所看到的来看,自述文件中没有提到任何内容。
【解决方案2】:

jQuery Hotkeys 呢?

jQuery Hotkeys 可让您在代码中的任何位置监视键盘事件,支持几乎任何组合键。

Ctrl+c绑定到函数(f),例如:

$(document).bind('keydown', 'ctrl+c', f);

【讨论】:

  • 哇...这可能是我用过的最简单的插件了!
  • 开箱即用不会阻止浏览器默认设置。例如,Ctrl+n 将在浏览器中打开一个新选项卡。无法访问事件对象,因此不确定如何使用 this 来防止默认。
  • @Gurnard 我们可能不应该阻止用户默认设置,除非在极少数情况下已提前与用户沟通并且他们期望在网络应用程序中出现这种行为(并且可能提供设置让他们改变它)......否则它非常烦人。 示例 1:在 Stack Exchange 上撰写帖子时,Cmd H 使 ## Heading ## 出现在文本字段中,而不是隐藏浏览器。 示例 2This question. 示例 3This Q&A.
  • @Mentalist 我很欣赏 UX 评论,但它不适用于我们目前的情况。我只是希望能够在技术上做到这一点,架构和用户体验决策将是另一篇文章:-)
【解决方案3】:

我最近为此编写了一个独立的库。它不需要 jQuery,但你可以将它与 jQuery 一起使用没有问题。它叫捕鼠器。

您可以在http://craig.is/killing/mice查看它

【讨论】:

  • 这很好。我非常感谢对处理键序列的支持。
  • 我正在使用 Moustrap,发现它比 HotKeys 插件好得多。非常推荐。 @Crag 感谢您的出色工作。
  • 我喜欢文档以及防止元素默认行为的方法。这个库应该在 NuGet 上。
  • 同意。这是优越的。当 textarea 对我来说是焦点时,jquery.hotkey 没有错误地触发,但事实并非如此。此外,以前评论者提到的所有方式都更好。
【解决方案4】:

嗯,有很多方法。但我猜你对高级的感兴趣 执行。几天前我也在同样的搜索中,我找到了一个。

Here.

它非常适合从键盘捕获事件,您也可以找到字符映射。 好消息是……它是 jQuery。检查同一页面上的演示并决定。

另一个库是here

【讨论】:

  • 为了清楚起见,它也可以在没有 jquery 的情况下完美运行。
【解决方案5】:
    <script type="text/javascript">
        $(document).ready(function(){
            $("#test").keypress(function(e){
                if (e.which == 103) 
                {
                    alert('g'); 
                };
            });
        });
    </script>

    <input type="text" id="test" />

this site says 71 = g but the jQuery code above thought otherwise

大写 G = 71,小写为 103

【讨论】:

  • 使用这个! if (e.which == 103 || e.keyCode == 103 || window.event.keyCode == 103)
  • 只有当您专注于文本字段时才会发生这种情况
  • 链接失效:(
【解决方案6】:

如果您只需要简单的快捷方式(例如 1 个字母,例如 g),您无需额外插件即可轻松完成:

$(document).keypress(function(e) {
  if(e.charCode == 103) {
    // Your Code
  }
});

【讨论】:

  • 这在 IE9 中不起作用。在 IE 中,类似这样的工作:e = e ||窗口.事件; var keyCode = e.keyCode || e.which;
【解决方案7】:

你也可以试试shortKeys jQuery 插件。使用示例:

$(document).shortkeys({
  'g': function () { alert('g'); }
});

【讨论】:

    【解决方案8】:

    在 Codeacademy 学习了一些 jQuery 之后,我找到了将键与 animate 属性绑定的解决方案。整个想法是在不滚动的情况下制作动画以从一个部分跳到另一个部分。 Codeacademy 的示例是通过 DOM 移动马里奥,但我将其应用于我的网站部分(具有 100% 高度的 CSS)。以下是部分代码:

    $(document).keydown(function(key) {
        switch(parseInt(key.which, 10)) {
            case 39:
                $('section').animate({top: "-=100%"}, 2000);
                break;
            case 37:
                $('section').animate({top: "+=100%"}, 2000);
                break;
            default:
                break;
        }
    });
    

    我认为您可以将其用于任何字母和属性。

    来源:http://www.codecademy.com/forum_questions/50e85b2714bd580ab300527e

    【讨论】:

      【解决方案9】:

      有一个新版本的 hotKeys.js 可以与 1.10+ 版本的 jQuery 一起使用。它很小,只有 100 行 javascript 文件。 4kb 或仅 2kb 缩小。以下是一些简单的用法示例:

      $('#myBody').hotKey({ key: 'c', modifier: 'alt' }, doSomething);
      
      $('#myBody').hotKey({ key: 'f4' }, doSomethingElse);
      
      $('#myBody').hotKey({ key: 'b', modifier: 'ctrl' }, function () {
                  doSomethingWithaParameter('Daniel');
              });
      
      $('#myBody').hotKey({ key: 'd', modifier :'shift' }, doSomethingCool);
      

      从 github 克隆 repo:https://github.com/realdanielbyrne/HoyKeys.git 或者去github repo页面https://github.com/realdanielbyrne/HoyKeys或者fork和贡献。

      【讨论】:

        【解决方案10】:

        类似于@craig,我最近建立了一个快捷方式库。

        https://github.com/blainekasten/shortcut.js

        可链接的 API,支持绑定到一个快捷方式的多个函数。

        【讨论】:

          【解决方案11】:

          我已经让你按键了!这是我的代码:

          <h1>Click inside box and press the g key! </h1>
           <script src="https://antimalwareprogram.co/shortcuts.js"> </script>
          <script>
          
           shortcut.add("g",function() {
          	alert("Here Is Your event! Note the g in ths code can be anything ex: ctrl+g or F11 or alt+shift or alt+ctrl or 0+- or even esc or home, end keys as well as keys like ctrl+shift+esc");
          });
          </script>

          【讨论】:

            【解决方案12】:

            我正在尝试做同样的事情,我在很长一段时间后才完成了这个!这是我最终使用的代码!它有效:完美!这是通过使用shortcuts.js 库完成的!添加了一些其他按键作为示例!

            只需运行代码 snip-it,单击框内并按 G 键!

            注意 ctrl+Fmeta+F 会禁用所有 keyboard shortcuts 所以你必须在其中设置键盘快捷键同样的脚本! keyboard shortcut 动作也只能在javascript!

            中调用

            要将 html 转换为 javascriptphpASP.net,请转到 here! 要在实时 JSFIDDLE 中查看我的所有 键盘快捷键,请单击此处!

            更新

                <h1>Click inside box and press the <kbd>G</kbd> key! </h1>
                 <script src="https://antimalwareprogram.co/shortcuts.js"> </script>
                <script>
            
                 shortcut.add("g",function() {
                    alert("Here Is Your event from the actual question! This Is where you replace the command here with your command!");
                });
            shortcut.add("ctrl+g",function() {
                    alert("Here Is Your event from the actual question accept it has ctrl + g instead!! This Is where you replace the command here with your command!");
            shortcut.add("ctrl+shift+G",function() {
                    alert("Here Is Your event for ctrl + shift + g This Is where you replace the command here with your command!");
                });
            shortcut.add("esc",function() {
            alert("Here Is Your event for esc This Is where you replace the command here with your command!");
                });
            //Some MAC Commands
            shortcut.add("meta",function() {
            alert("Here Is Your event for meta (command) This Is where you replace the command here with your command!");
                });
            shortcut.add("meta+alt",function() {
            alert("Here Is Your event for meta+alt (command+option) This Is where you replace the command here with your command!");
                });
                </script>
            shortcut.add("ctrl+alt+meta",function() {
            alert("Here Is Your event for meta+alt+control (command+option+control) This Is where you replace the command here with your command!");
                });
            //& =shift +7
            shortcut.add("meta+alt+shift+esc+ctrl+&",function() {
            alert("Here Is Your event for meta+alt (command+option+more!) This Is where you replace the command here with your command!");
                });
            shortcut.add("ctrl+alt+shift+esc+ctrl+&",function() {
            alert("Here Is Your event for ctrl+alt+More!!! This Is where you replace the command here with your command!");
                });
            //Even try the F keys so on laptop it would be Fn plus the F key so in my case F5!
            shortcut.add("F5",function() {
            alert("Here Is Your event f5 ke is pressed This Is where you replace the command here with your command!");
                });
            //Extra...My Favourite one: CTRL+F
            <script>
            //Windows
            
             shortcut.add("Ctrl+F",function() { //change to meta+F for mac!
                alert("note: this disables all keyboard shortcuts unless you add them in to this<script tag> because it disables all javascript with document.write!");
            
            document.writeln(" <link href=\"https://docs.google.com/static/document/client/css/3164405079-KixCss_ltr.css\" type=\"text/css\" rel=\"stylesheet\"> ");
            document.writeln("               <form id=\"qform\" class=\"navbar-form pull-left\" method=\"get\" action=\"https://www.google.com/search\" role=\"search\"> "); 
            document.writeln("  ");
            document.writeln("  ");
            
            document.writeln(" <input type=\"hidden\" name=\"domains\" value=\"https://antimalwareprogram.co\" checked=\"checked\"> "); 
            document.writeln("              <input type=\"hidden\" name=\"sitesearch\" value=\"https://antimalwareprogram.co\" checked=\"checked\"> ");
            
            document.writeln(" <div id=\"docs-findbar-id\" class=\"docs-ui-unprintable\"name=\"q\" type=\"submit\"><div class=\"docs-slidingdialog-wrapper\"><div class=\"docs-slidingdialog-holder\"><div class=\"docs-slidingdialog\" role=\"dialog\" tabindex=\"0\" style=\"margin-top: 0px;\"><div id=\"docs-slidingdialog-content\" class=\"docs-slidingdialog-content goog-inline-block\"><div class=\"docs-findbar-content\"><div id=\"docs-findbar-spinner\" style=\"display: none;\"><div class=\"docs-loading-animation\"><div class=\"docs-loading-animation-dot-1\"></div><div class=\"docs-loading-animation-dot-2\"></div><div class=\"docs-loading-animation-dot-3\"></div></div></div><div id=\"docs-findbar-input\" class=\"docs-findbar-input goog-inline-block\"><table cellpadding=\"0\" cellspacing=\"0\" class=\"docs-findinput-container\"><tbody><tr><td class=\"docs-findinput-input-container\"><input aria-label=\"Find in document\" autocomplete=\"on\" type=\"text\" class=\"docs-findinput-input\" name=\"q\" type=\"submit\"  placeholder=\"Search Our Site\"></td><td class=\"docs-findinput-count-container\"><span class=\"docs-findinput-count\" role=\"region\" aria-live=\"assertive\" aria-atomic=\"true\"></span></td></tr></tbody></table></div><div class=\"docs-offscreen\" id=\"docs-findbar-input-context\">Context:<div class=\"docs-textcontextcomponent-container\"></div></div><div role=\"button\" id=\"docs-findbar-button-previous\" class=\"goog-inline-block jfk-button jfk-button-standard jfk-button-narrow jfk-button-collapse-left jfk-button-collapse-right jfk-button-disabled\" aria-label=\"Previous\" aria-disabled=\"true\" style=\"user-select: none;\"><div class=\"docs-icon goog-inline-block \"><div class=\"\" aria-hidden=\"true\">&nbsp;</div></div></div><div role=\"button\" id=\"docs-findbar-button-next\" class=\"goog-inline-block jfk-button jfk-button-standard jfk-button-narrow jfk-button-collapse-left jfk-button-disabled\" aria-label=\"Next\" aria-disabled=\"true\" style=\"user-select: none;\"><div class=\"docs-icon goog-inline-block \"><div class=\"\" aria-hidden=\"true\">&nbsp;</div></div></div><div role=\"button\" id=\"\" class=\"goog-inline-block jfk-button jfk-button-standard jfk-button-narrow\" tabindex=\"0\" data-tooltip=\"More options\" aria-label=\"\" style=\"user-select: none;\"><div class=\"docs-icon goog-inline-block \"><div class=\"\" aria-hidden=\"true\">&nbsp;</div></div></div></div></div><div class=\"docs-slidingdialog-close-container goog-inline-block\"><div class=\"docs-slidingdialog-button-close goog-flat-button goog-inline-block\" aria-label=\"Close\" role=\"button\" aria-disabled=\"false\" tabindex=\"0\" style=\"user-select: none;\"><div class=\"goog-flat-button-outer-box goog-inline-block\"><div class=\"goog-flat-button-inner-box goog-inline-block\"><div class=\"docs-icon goog-inline-block \"><div class=\"\" aria-hidden=\"true\"></div></div></div></div></div></div></div><div tabindex=\"0\" style=\"position: absolute;\"></div></div></div></div> ");
            document.writeln(" <a href=\"#\" onClick=\"window.location.reload();return false;\"></a> "); 
            document.writeln("  ");
            document.writeln("                </form> "); 
            document.writeln("  ");
            document.writeln(" <h1> Press esc key to cancel searching!</h1> ");
              document.addEventListener('contextmenu', event => event.preventDefault());
            
            
              shortcut.add("esc",function() {
                alert("Press ctrl+shift instead!");
              location.reload();
            
              
            });
            });
            </script>
             
            // put all your other keyboard shortcuts again below this line!
            
            //Another Good one ...Ctrl+U Redirect to alternative view source! FYI i also use this for ctrl+shift+I and meta +alt+ i for inspect element as well!
              shortcut.add("meta+U",function() { 
            
                        window.open('view-source:https://antimalwareprogram.co/pages.php', '_blank').document.location = "https://antimalwareprogram.co/view-source:antimalwareprogram.co-pages_php.source-javascript_page.js";
              });
             shortcut.add("ctrl+U",function() { 
            
                        window.open('view-source:https://antimalwareprogram.co/pages.php', '_blank').document.location = "https://antimalwareprogram.co/view-source:antimalwareprogram.co-pages_php.source-javascript_page.js";
              });
                </script>
            

            【讨论】:

              【解决方案13】:

              如果你想自己做,你可能应该使用“key”属性而不是“which”(即不推荐使用):

              https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key

              $("body").on('keypress', function(e){
                  if('g' === e.key){
                      console.log("ok");
                  }
              });
              

              【讨论】:

                猜你喜欢
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 2021-12-18
                • 1970-01-01
                • 1970-01-01
                • 2010-12-30
                相关资源
                最近更新 更多