Javascript - How to create a keypress event?

心不动则不痛 提交于 2021-02-05 12:21:01

问题


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.

I've found this and tried it: https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/KeyboardEvent

$(document).ready(function () {
    var x = new KeyboardEvent("FormatCode", deprectiatedArgument);
});

But after further inspection the KeyboardEventInit is depreciated.

I would like to create an event on pres of the CTRL + K keys.


回答1:


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



回答2:


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>



回答3:


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.




回答4:


$(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



来源:https://stackoverflow.com/questions/38483865/javascript-how-to-create-a-keypress-event

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