Javascript - How to create a keypress event?

后端 未结 4 1273
误落风尘
误落风尘 2021-01-29 09:24

I\'ve looked on the internet for this and all I can find are depreciated functions so before posting please check to make sure that the code you suggest isn\'t depreciated.

相关标签:
4条回答
  • 2021-01-29 10:01

    You have a specific key code for every button on the keyboard. All of them are here http://keycode.info/.

    $(document).keyup(function(e) {
        if (e.keyCode === 13) function();   // enter
        if (e.keyCode === 27) function();   // esc
    });
    
    0 讨论(0)
  • 2021-01-29 10:08
    $(document).ready(function () {
        var bool = false;
        $(document).keydown(function (e) {
            if (e.keyCode === 17) {
                bool = true;
            }
            if (bool == true && e.keyCode == 75) {
                alert("");
            }
        });
        $(document).keyup(function (e) {
            if (e.keyCode === 17) {
                bool = false;
            }
        });
    });
    

    This is how me and a friend got it working

    0 讨论(0)
  • 2021-01-29 10:17

    you can use a library called shortcut.js .. here is a link to their source code for downloading: http://www.openjs.com/scripts/events/keyboard_shortcuts/shortcut.js

    then run ur code by making this function:

    shortcut.add("Ctrl+K",function() {
        alert("Hi there!");
    });
    

    and here is the documentation : http://www.openjs.com/scripts/events/keyboard_shortcuts/

    hope that can help.

    0 讨论(0)
  • 2021-01-29 10:23

    Here's a vanilla JS solution to detect a CTRL + k keypress event:

    UPDATED to also trigger the event.

    document.addEventListener("keypress", function(e) {
      if ((e.ctrlKey || e.metaKey) && (e.keyCode == 11 || e.keyCode == 75)) {
        alert("ctrl+k!");
      }
    });
    
    
    document.getElementById("trigger").addEventListener("click", function(){
      //trigger a keypress event...
      var e = document.createEvent('HTMLEvents');
        e.initEvent("keypress", false, true);
        e.ctrlKey = true;
        e.keyCode = 75;
      document.dispatchEvent(e);
    });
    Press <kbd>ctrl+k</kbd> or
    <a href="#" id="trigger">trigger the event</a>

    0 讨论(0)
提交回复
热议问题