event.js 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. export function createEvent (type, name) {
  2. const e = document.createEvent(type || 'Event')
  3. e.initEvent(name, true, true)
  4. return e
  5. }
  6. export function dispatchTouch (target, name = 'touchstart', touches) {
  7. const event = createEvent('', name)
  8. event.touches = event.targetTouches = event.changedTouches = Array.isArray(touches) ? touches : [touches]
  9. target.dispatchEvent(event)
  10. }
  11. export function dispatchTouchStart (target, touches) {
  12. dispatchTouch(target, 'touchstart', touches)
  13. }
  14. export function dispatchTouchMove (target, touches) {
  15. dispatchTouch(target, 'touchmove', touches)
  16. }
  17. export function dispatchTouchEnd (target, touches) {
  18. dispatchTouch(target, 'touchend', touches)
  19. }
  20. export function dispatchSwipe (target, touches, duration, cb) {
  21. if (!Array.isArray(touches)) {
  22. touches = [touches]
  23. }
  24. dispatchTouchStart(target, touches[0])
  25. const moveAndEnd = () => {
  26. dispatchTouchMove(target, touches[1] || touches[0])
  27. dispatchTouchEnd(target, touches[2] || touches[1] || touches[0])
  28. cb && cb()
  29. }
  30. if (duration) {
  31. setTimeout(moveAndEnd, duration)
  32. } else {
  33. moveAndEnd()
  34. }
  35. }