Javascript keycode clash: “right arrow” and “single quote”

后端 未结 4 1206
伪装坚强ぢ
伪装坚强ぢ 2021-01-14 07:06

The following script does what it should, that is, it reacts on the keys \"arrow left\" and \"arrow right\". However, due to a keycode clash, it reacts on a single quote as

4条回答
  •  花落未央
    2021-01-14 07:38

    Use keydown instread of keypress

    jS:

    document.onkeydown=function(event){
      if(window.event) event=window.event;
      var keycode=(event.keyCode)?event.keyCode:event.which;
      switch(keycode){
        case 37: alert("an arrow");
          break;
        case 39: alert("another arrow");
          break;
      }
    }
    

    Fiddle : http://jsfiddle.net/p9x1Lj4u/2/

提交回复
热议问题