JavaScript equivalent of jQuery's keyup() and keydown()

走远了吗. 提交于 2019-12-07 10:31:13

问题


I have seen this link on stackoverflow: $(document).ready equivalent without jQuery

In my context I am using

$(document).keydown(Keypress);
$(document).keyup(Keyoff);

for the functions

 function Keypress(evt) {
     if (evt.keyCode == 39) rightpress = true;
     else if (evt.keyCode == 37) leftpress = true;
 }

 //unset
 function Keyoff(evt) {
     if (evt.keyCode == 39) rightpress = false;
     else if (evt.keyCode == 37) leftpress = false;
 }

Is there a javascript equivalent? Like window.onload?


回答1:


In order to use some more "equivalent" to jQuery's on method, you shouldn't use the onkeydown and onkeyup handlers. Use addEventListener or attachEvent. attachEvent is specifically for older versions of IE, so addEventListener is the standard and is used by all other browsers. But you should always include support, so you can make a function to handle it all. Try:

function addEvent(element, eventName, callback) {
    if (element.addEventListener) {
        element.addEventListener(eventName, callback, false);
    } else if (element.attachEvent) {
        element.attachEvent("on" + eventName, callback);
    }
}

addEvent(window, "keydown", Keypress);
addEvent(window, "keyup", Keyoff);

This allows you to add multiple handlers, just like jQuery's on method does. Setting the .onkeydown and .onkeyup properties allows only one handler (unless you want to overwrite another). There's a lot more that the addEvent function could do, to make a standard, cross-browser event handling (an example is what happens based on the return type of the callback). It's really not important for now - if you want complete cross browser compatibility, that's what jQuery's for :)

References:

  • addEventListener: https://developer.mozilla.org/en-US/docs/DOM/EventTarget.addEventListener
  • addEventListener vs onclick



回答2:


window.onkeydown = Keypress;
window.onkeyup = Keyoff;

https://developer.mozilla.org/en-US/docs/DOM/window.onkeyup

https://developer.mozilla.org/en-US/docs/DOM/window.onkeydown



来源:https://stackoverflow.com/questions/16493645/javascript-equivalent-of-jquerys-keyup-and-keydown

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