How do I programmatically create a TouchEvent in Chrome ?[JavaScript jQuery 模拟点击操作]


/* eventType is 'touchstart', 'touchmove', 'touchend'... */
function sendTouchEvent(x, y, element, eventType) {
  const touchObj = new Touch({
    identifier: Date.now(),
    target: element,
    clientX: x,
    clientY: y,
    radiusX: 2.5,
    radiusY: 2.5,
    rotationAngle: 10,
    force: 0.5,
  });

  const touchEvent = new TouchEvent(eventType, {
    cancelable: true,
    bubbles: true,
    touches: [touchObj],
    targetTouches: [],
    changedTouches: [touchObj],
    shiftKey: true,
  });

  element.dispatchEvent(touchEvent);
}

const myElement = document.getElementById('foo')

sendTouchEvent(150, 150, myElement, 'touchstart');
sendTouchEvent(220, 200, myElement, 'touchmove');
sendTouchEvent(220, 200, myElement, 'touchend');

To test if a given browser supports Touch and TouchEvent

if (typeof Touch !== 'undefined' &&
    typeof TouchEvent !== 'undefined' &&
    Touch.length === 1 &&
    TouchEvent.length === 1) {
       sendTouchEvent(200, 200, myElement, 'touchmove');
}

see Touch and TouchEvent constructors

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 13,501评论 0 23
  • NAME dnsmasq - A lightweight DHCP and caching DNS server....
    ximitc阅读 7,956评论 0 0
  • 昨天晚上,王宝强的“离婚声明”像一颗炸弹扔上了夜空。一群网友开始形成了专业观光团,路线图基本为:王宝强——马蓉——...
    艾歌_阅读 3,240评论 0 0
  • 就这样爱着你 当我知道我们不在同一个大学时,我就知道我必须付出比别人多好几倍的努力才能和你在一起。因此我不要电脑,...
    六道鼬阅读 3,555评论 12 4
  • 说的多好啊
    欣昉阅读 1,261评论 1 1

友情链接更多精彩内容