Javascript 键码冲突:"right arrow" 和 "single quote"

Javascript keycode clash: "right arrow" and "single quote"

下面的脚本做了它应该做的事情,也就是说,它对 "arrow left" 和 "arrow right" 键做出反应。但是,由于键码冲突,它也会对单引号做出反应。这使得无法将该字符输入到输入字段中。对此有什么办法吗?

<script type="text/javascript">
  onload = 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>

因为它是文本输入,所以当有人试图使用箭头键在输入中移动光标时,您似乎也会遇到问题。因此,应该使用停止事件propagation/bubbling,并且可以解决您所询问的主要问题。

// assuming you've grabbed an input in var input_ele
input_ele.onkeypress = function (e) {
    e = e || window.event;

    if (e.stopPropagation) {
        e.stopPropagation();
    } else {
        e.cancelBubble = true;
    }
};

使用它会阻止 keypress 事件离开输入元素,从而永远不会到达文档元素以触发不需要的行为。换句话说,您不会破坏非常标准的控件元素的预期行为。

使用[=h11=]代替keypress

iS:

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/

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

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

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

当 属性 存在于事件对象中并且 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:其他评论者和答案是正确的。我忘了你不应该用 keypress 事件检测控制键。改为 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>

keypress 不应捕获像 left/right 箭头这样的控制键。如果你使用keydown事件,单引号键码是222绝对没有冲突