Javascript键码冲突:“右箭头”和“单引号”

以下脚本执行它应该做的事情,也就是说,它对“向左箭头”和“向右箭头”键做出反应.但是,由于键码冲突,它也会对单引号做出反应.这使得无法将该字符输入到输入字段中.可以做些什么吗?

<script type="text/javascript">
  onl oad = function(){
    document.onkeypress=function(e){
      if(window.event) e=window.event;
      var keycode=(e.keyCode)?e.keyCode:e.which;

      switch(keycode){
        case 37: window.location.href='set.jsp?index=5';
          break;
        case 39: window.location.href='set.jsp?index=7';
          break;
      }
    }
  }
</script>

解决方法:

当用户按下单引号键时,e.keyCode属性为零,e.which属性为39.执行String.fromCharCode(39)返回单引号.

如果该属性在事件对象中,您需要keyCode:

var keycode = "keyCode" in e ? e.keyCode : e.which;

这样,当事件对象中存在该属性时,以及当该属性也存在时,keyCode为零.

document.onkeydown = function(event) {
    event = event || window.event;

    var keyCode = "keyCode" in event ? event.keyCode : event.which;

    switch (keyCode) {
        case 37: console.log("37 was pressed", event); break;
        case 39: console.log("39 was pressed", event); break;
    }
};

编辑#1:其他评论者和答案是正确的.我忘了你不应该用按键事件检测控制键.改为onkeydown.

跨浏览器的完整HTML示例:

<!DOCTYPE HTML>
<html>
<head>
    <meta charset="utf-8">
    <title>Key Codes Test</title>
</head>
<body>
    <script type="text/javascript">
        document.onkeydown = function(event) {
            event = event || window.event;

            var keyCode = "keyCode" in event ? event.keyCode : event.which;

            switch (keyCode) {
                case 37: console.log("37 was pressed", event); break;
                case 39: console.log("39 was pressed", event); break;
            }
        };
    </script>
    <input type="text" size="30">
</body>
</html>
上一篇:键盘事件


下一篇:unity 控制物体移动的三种方法之美