将触摸事件转换为鼠标事件仅适用于每秒一次

时间:2016-04-26 16:04:12

标签: javascript mouseevent touch-event

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

所以这是我的功能here

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'等等。任何人都知道为什么会这样?

1 个答案:

答案 0 :(得分:0)

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