簡體   English   中英

使用 JavaScript 以編程方式調度鍵盤(例如按鍵)事件

[英]Programmatically dispatch keyboard (e.g. keypress) events using JavaScript

我正在嘗試以編程方式為鍵盤和鼠標事件調度事件。

到目前為止,我嘗試過的東西很少。 現在我能夠以編程方式調度鼠標事件並查看更改:

const element = document.getElementById("element");
const event = new Event('click', {bubbles: true});
element.dispatchEvent(event);

上述方法適用於Mouse Event 我已經嘗試了以下鍵盤事件的方法:

const element = document.getElementById("input-element");
const event = new KeyboardEvent('keypress', {'key': 'e'});
element.dispatchEvent(event);

這里似乎正在執行事件,但輸入字段中的值並未更新。

當您按下某個鍵時,會發生許多事件。 它們都不會導致輸入值被更改,但您可以使用此函數來近似按下某個鍵時發生的情況。

 const element = document.getElementById("input-element"); const key = 'e'; var success = triggerKey(key, element); console.log(success?'success':'fail'); function triggerKey(key, element){ if(!/^[az]$/.test(key)) return false; if(!['INPUT','TEXTAREA'].includes(element.tagName)) return false; const events = ['keydown', 'keypress', 'textInput', 'keyup']; events.forEach(event_name=>{ const opts = 'textInput' === event_name ? { inputType: 'insertText', data: key } : { key: key, code: `Key${key.toUpperCase()}` }; const event = 'textInput' === event_name ? new InputEvent('input', opts) : new KeyboardEvent(event_name, opts); element.dispatchEvent(event); if('textInput' === event_name) element.value += key; }); return true; }
 <input id="input-element">

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM