繁体   English   中英

使用 JavaScript 使用数据触发键盘事件

[英]Triggering Keyboard events with data using JavaScript

这似乎是一个重复的问题。 但是我搜索了很多地方,我无法找到使用普通 javascript(不使用 jQuery)发送事件数据的正确示例。

https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent没有任何示例。

我需要这样的东西。 https://developer.mozilla.org/en-US/docs/Web/Guide/Events/Creating_and_triggering_events#Adding_custom_data_.E2.80.93_CustomEvent

例子:

// listening for keypress event,    
ele.addEventListener("keydown", function(e){
    console.log(e.keyCode); //expecting 50
});


// triggering like this
var e = new KeyboardEvent("keydown", {keyCode: 50});
ele.dispatchEvent(e);

借助Axel Rauschmayer博士的精彩文章http://www.2ality.com/2013/06/triggering-events.html

您可以使用以下3个构造函数进行触发,

// use any one of these constructor as per your usecase

var e = new Event("keydown"); //without any data
var e = new CustomEvent("keydown", {detail: {prop1: "value"}}); //if any data required use detail: only detail/bubbles/cancelable properties can be passed here
var e = new KeyboardEvent("keydown");

// add properties

e.keyCode = 50; // works for *Event* and *CustomEvent* constructors
e.key = 50; // in *KeyboardEvent* constructor *keyCode* is **readonly** property so use *key* property. Refer properties detail using https://developer.mozilla.org/en-US/docs/Web/Reference/Events/keydown
e.anyNewProp = "value"; // if any new prop is required

// finally dispatchEvent using dispatchEvent method of dom element

ele.dispatchEvent(e);
 // listening for keypress event, ele.addEventListener("keydown", function(e){ console.log(e.keyCode); //results 50 console.log(e.key); //results 50 console.log(e.anyNewProp); //results "value" }); 

使用本机KeyboardEvent构造函数最有意义。 但是,@Darshan 的示例在 2022 年不再适用于更新的浏览器,因为事件的属性是只读的(developer.mozilla.org) ,相反,您必须将初始化程序字典传递给构造函数:

// ! Note that KeyboardEvent.keyCode are deprecated as of 2022
const keyPressCode50 = new KeyboardEvent('keypress', {keyCode: 50});
element.dispatch(keyPressCode50);

// Equivalently, you can initialize the `key` or depending on the where its used, multiple properties.
const keyPressKey2   = new KeyboardEvent('keypress', {key: '2', code: 'Digit2'};
element.dispatch(keyPressKey2);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM