javascript - 拦截箭头键并发送 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>
解决方案
实际上只是想通了...你不能。
https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent
注意:手动触发事件不会生成与该事件关联的默认操作。例如,手动触发键事件不会导致该字母出现在焦点文本输入中。对于 UI 事件,出于安全原因,这很重要,因为它可以防止脚本模拟与浏览器本身交互的用户操作。
推荐阅读
- python - 你能帮我解决这个错误吗?AttributeError:“numpy.ndarray”对象没有属性“键”
- python - 如何在 tqdm 上打印进度条?
- python - 熊猫:在一行中向数据框添加几列
- r - R:树形图分类自定义颜色(正 - 绿色,负 - 红色)
- .net - 需要帮助来正则表达式从 2 页组合的文本
- hyperledger-fabric - Hyperledger Fabric,如何与另一个对等节点共享私有数据?
- html - 如何使背景连续?
- firebase - 为什么我在我的代码函数中收到此错误返回 null?
- auth0 - 电容:应用内导航 + 自定义 URL 重定向
- pandas - 熊猫中包含某些字符串的列的总和值