首页 > 解决方案 > 拦截箭头键并发送 Enter 代替

问题描述

使用纯 JS 我想拦截箭头键并在其位置发送回车键以提交表单。正在发送回车键,当您在键盘上物理按下回车键时,它的行为与回车键不同,我知道我可以用click()它来做同样的事情,这真的让我很困扰,因为我无法让回车键工作我预计..

见小提琴

var input = document.getElementById('name');
input.addEventListener('keydown', e => handleArrowNavigation(e));

function handleArrowNavigation(event) {
  if (event.key === "ArrowRight") {
    //send enter to expand
    triggerEnterKey(event.target.id);
  }
}

function triggerEnterKey(elementId) {
  var element = document.getElementById(elementId);
  if (element) {
    const keyEvent = new KeyboardEvent("keydown", {
      key: "Enter",
      //code: "Enter",
      //keyCode: 13,
      //charCode: 13,
      //type: "keydown",
      //isTrusted: true,
      //defaultPrevented: true,
      //currentTarget: element,
      //view: window,
      //bubbles: true
    });

    var dispatched = element.dispatchEvent(keyEvent);
    console.log("enter key triggered on element: " + element.id);
    console.log("event dispatched: ", dispatched);

    //element.click();//click works
  }
}
<form action="javascript: alert('form submitted.')">
  <p>
    If you hit enter while focus is on the input you will get an alert as expected. If you click the right arrow key I'd like it to trigger the enter key and do what enter does. (right arrow key should trigger form submission alert)
  </p>
  <input type="text" id="name" />
  <input type="submit" id="submit" />
</form>

标签: javascriptdom-events

解决方案


实际上只是想通了...你不能。

https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent

注意:手动触发事件不会生成与该事件关联的默认操作。例如,手动触发键事件不会导致该字母出现在焦点文本输入中。对于 UI 事件,出于安全原因,这很重要,因为它可以防止脚本模拟与浏览器本身交互的用户操作。


推荐阅读