模拟按钮的单击事件
const btn = document.querySelector('.logo');
const event = new MouseEvent('click', {
bubbles:true,
cancelable:true,
view:window
});
btn.dispatchEvent(event)
具体的参数参考这里。
同样的,模拟键盘事件应该使用KeyboardEvent
构造函数
event = new KeyboardEvent(typeArg, KeyboardEventInit);
模拟键盘事件的例子
const event = new KeyboardEvent('keydown', {
altKey: true,
bubbles: true,
cancelable: true,
code: 'KeyK',
composed: true,
ctrlKey: true,
key: 'k',
metaKey: true,
repeat: true,
shiftKey: true,
view: window
})
document.addEventListener('keydown', (e) =>{
console.log(e.key)
})
document.dispatchEvent(event);
// k
参考
- MSDN - MouseEvent()
- MSDN - dispatchEvent
- MSDN - 键盘事件 KeyboardEvent()
- LoadingMore's Blog - 原生JS模拟点击事件和自定义事件
- QingRong - 创建、初始化事件