防止keydown事件javascript

时间:2018-09-03 11:03:53

标签: javascript

你好,我只是想知道是否可以防止键盘按下事件发生,如果输入焦点对准并输入

window.addEventListener("onkeydown", keyDown, true);
window.addEventListener("keydown", keyDown);

function keyDown() {
  var e = window.event;
  switch (e.keyCode) {
    case 188:
      runon();
      break;
    case 190:
      runoff();
      break;
    case 187:
      partyon();
      break;
    case 189:
      partyoff();
      break;
    case 192:
      leaderboard();
      break;
  }
}
<input type="text" name="message" class="chat-input" placeholder="Enter your chat message..." maxlength="140">

1 个答案:

答案 0 :(得分:0)

您可以像这样简单地在e.preventDefault();块中添加default,它将达到目的:

switch (e.keyCode) {
case 188:
  runon();
  break;
case 190:
  runoff();
  break;
case 187:
  partyon();
  break;
case 189:
  partyoff();
  break;
case 192:
  leaderboard();
  break;
default:
 e.preventDefault();

}

希望这会有所帮助。