trigger-event.ts 694 B

1234567891011121314151617181920212223242526272829
  1. /**
  2. * Trigger event
  3. * mouseenter, mouseleave, mouseover, keyup, change, click
  4. */
  5. const triggerEvent = (elm: Element, name: string, ...opts: any[]) => {
  6. let eventName: string
  7. if (/^mouse|click/.test(name)) {
  8. eventName = 'MouseEvents'
  9. } else if (name.startsWith('key')) {
  10. eventName = 'KeyboardEvent'
  11. } else {
  12. eventName = 'HTMLEvents'
  13. }
  14. const evt = document.createEvent(eventName)
  15. evt.initEvent(name, ...opts)
  16. if (name === 'keydown' && opts[0]) {
  17. // trigger event with keycode
  18. // triggerEvent(ele, 'keydown', 'ArrowDown')
  19. Object.defineProperty(evt, 'code', { value: opts[0] })
  20. }
  21. elm.dispatchEvent(evt)
  22. return elm
  23. }
  24. export default triggerEvent