在香草JS中触发Enter键

时间:2018-08-09 20:27:13

标签: javascript

我试图在我的输入上触发Enter键输入事件,而没有实际按下Enter键,更确切地说是onload。

我发现initKeyboardEventinitKeyEvent均已弃用,甚至从网络标准中删除了keyCode和e。which

I also found this post讨论了如何在jQuery中执行此操作。但是,我一直在尝试找出如何在香草JS中做到这一点,但是没有运气。

var txtbox = document.getElementById('txtbox');
txtbox.onkeydown = function(e) {
  if (e.keyCode == 13) {
    alert('enter key pressed');
  }
  e.preventDefault();
};

var ev = document.createEvent('KeyboardEvent');
// Send key '13' (= enter)
ev.initKeyboardEvent(
    'keydown', true, true, window, false, false, false, false, 13, 0);
document.body.dispatchEvent(ev);
<input type="text" id="txtbox" placeholder="trigger enter key press">

1 个答案:

答案 0 :(得分:4)

由于不赞成使用initKeyboardEvent,请改用构造函数: https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent

event.key没有被弃用,因此我们可以使用key ===“ Enter”

还触发在txtbox而非正文上输入

var txtbox = document.getElementById('txtbox');
txtbox.onkeydown = function(e) {
  if (e.key == "Enter") {
    alert('enter key pressed');
  }
  e.preventDefault();
};

var ev = new KeyboardEvent('keydown', {altKey:false,
  bubbles: true,
  cancelBubble: false, 
  cancelable: true,
  charCode: 0,
  code: "Enter",
  composed: true,
  ctrlKey: false,
  currentTarget: null,
  defaultPrevented: true,
  detail: 0,
  eventPhase: 0,
  isComposing: false,
  isTrusted: true,
  key: "Enter",
  keyCode: 13,
  location: 0,
  metaKey: false,
  repeat: false,
  returnValue: false,
  shiftKey: false,
  type: "keydown",
  which: 13});

txtbox.dispatchEvent(ev);