js模拟键盘事件

2021-09-04

function fireKeyEvent(el: HTMLElement, evtType: string, keyChar: string, keyCode: number) {
    el.focus()
    const KeyboardEventInit = {key: keyChar, code: keyChar, location: 0, repeat: false,
      isComposing: false, bubbles: true, composed: true, charCode: keyCode, keyCode: keyCode}
    const evtObj: any = new KeyboardEvent(evtType, KeyboardEventInit)
    evtObj.stop = evtObj.stopPropagation
    el.dispatchEvent(evtObj)
  }
fireKeyEvent(target, 'keydown', 'ArrowUp', 38)

虽然MDN上说charCodekeyCode已废弃,但是KeyboardEventInit中不加这2个配置,这个事件根本就触发不了

你可能感兴趣的:(js模拟键盘事件)