将触摸事件转换为鼠标事件仅每秒有效一次

convert touch event to mouse events only works every second time

本文关键字:事件 有效 一次 转换 触摸 鼠标      更新时间:2023-09-26

我正在使用以下脚本将触摸事件转换为鼠标事件。它工作得很好,但是在两个触摸事件之间(例如,平移图表的数据),不会触发第二个事件。然后触发下一个事件,不触发下一个事件,依此类推。

所以这是我在这里找到的功能

function touchHandler(event)
{
    var touches = event.changedTouches,
        first = touches[0],
        type = "";
    switch(event.type)
    {
        case "touchstart": type = "mousedown"; break;
        case "touchmove":  type = "mousemove"; break;        
        case "touchend":   type = "mouseup";   break;
        default:           return;
    }
    // initMouseEvent(type, canBubble, cancelable, view, clickCount, 
    //                screenX, screenY, clientX, clientY, ctrlKey, 
    //                altKey, shiftKey, metaKey, button, relatedTarget);
    var simulatedEvent = document.createEvent("MouseEvent");
    simulatedEvent.initMouseEvent(type, true, true, window, 1, 
                                  first.screenX, first.screenY, 
                                  first.clientX, first.clientY, false, 
                                  false, false, false, 0/*left*/, null);
    first.target.dispatchEvent(simulatedEvent);
    event.preventDefault();
}
function init() 
{
    document.addEventListener("touchstart", touchHandler, true);
    document.addEventListener("touchmove", touchHandler, true);
    document.addEventListener("touchend", touchHandler, true);
    document.addEventListener("touchcancel", touchHandler, true);    
}

有谁知道为什么这种行为是这样的?

更新:我发现,"first.target"首先是"div.dragcover",在第二次尝试中,它是"rect",然后再次是"div.dragcover",依此类推。有人知道为什么会这样吗?

听起来几乎像是标记有问题。目标应始终是手指实际触摸的元素。