Javascript - How to create a keypress event?

后端 未结 4 1277
误落风尘
误落风尘 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: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 ctrl+k or
    trigger the event

提交回复
热议问题