使用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);
相关文章:
- 用程序搜索JQuery数据表中的文本
- 要求输入在数据列表中
- 正在将数据主题添加到所有项目
- 函数参数中的数据与指定变量之间的任何性能差异
- 在VanillaJS中模拟模型双向数据绑定
- CSS-如何定位内容数据标题
- 使用电话间隙在Android应用程序中显示SQL Lite的数据
- 无法在数据endVal中设置值=“”;{{ucount}}”;使用Angular JS的CountUp
- 序列化数据属性中对象的最可靠方法
- 如何将JSON数据导入我的ejs模板
- 不显示带有本地json文件数据的谷歌地图脚本
- 如何将json数据显示为html
- 画布数据到图像
- 使用jquery将mysql数据获取到新的表行中
- 使用html中的外部javascript进行数据验证
- 有时数据是't显示在浏览器中
- 收听蓝牙键盘的原始数据
- 下拉模型数据未设置和使用键盘更改问题
- 使用JavaScript触发带有数据的键盘事件
- 如何使用getJSON将键盘数据发送到服务器