JS模拟Touch事件

本文介绍了如何使用JavaScript来模拟Touch事件。通过理解WebAPI中的Touch和TouchEvent对象,结合MDN文档和StackOverflow上的讨论,可以创建和处理触摸事件,这对于在浏览器环境中实现触屏设备的交互至关重要。
        var ele =  document.getElementsByClassName('target_node_class')[0]
        //may have x and y properties in some browsers,But it always has left, top, right, and bottom properties.
        var rect = ele.getBoundingClientRect(); 
        var touch = new Touch({
            "identifier" : 0,
            "target" : ele,
            "clientX" : (rect.left + rect.right)/2,
            "clientY" : (rect.top + rect.bottom)/2,
            "screenX" : (rect.left + rect.right)/2,
            "screenY" : (rect.top + rect.bottom)/2,
            "pageX" : (rect.left + rect.right)/2,
            "pageY" : (rect.top + rect.bottom)/2,
            "radiusX" : 11.5,
            "radiusY" : 11.5,
            "rotationAngle" : 0.0,
            "force" : 1});
        
        var touchstart = new TouchEvent("touchstart", {
            cancelable: true,
            bubbles: true,
            composed: true,
            touches: [touch],
            targetTouches: [touch],
            changedTouches: [touch]
        });
        
        var touchend = new TouchEvent("touchend", {
            cancelable: true,
            bubbles: true,
            composed: true,
            touches: [touch],
            targetTouches: [touch],
            changedTouches: [touch]
        });
        
        ele.dispatchEvent(touchstart);
        ele.dispatchEvent(touchend);

相关WebAPI
Touch: https://developer.mozilla.org/en-US/docs/Web/API/Touch/Touch
TouchEvent: https://developer.mozilla.org/en-US/docs/Web/API/TouchEvent/TouchEvent
stackoverflow上类似的问题:https://stackoverflow.com/questions/29018151/how-do-i-programmatically-create-a-touchevent-in-chrome-41/42447620

转载于:https://www.cnblogs.com/jeromeblog/p/11404325.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值