【问题标题】:convert touch event to mouse events only works every second time将触摸事件转换为鼠标事件仅每秒钟有效
【发布时间】:2016-08-20 14:12:31
【问题描述】:

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

所以这是我找到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”,依此类推。有人知道为什么会这样吗?

【问题讨论】:

  • 您似乎没有将 touchcancel 事件转换为 mouseevent。这是故意的吗?
  • 我真的不需要 touchcancel 事件,我不知道应该绑定哪个鼠标事件,有什么想法吗?
  • initMouseEvent 已弃用:developer.mozilla.org/en-US/docs/Web/API/MouseEvent/… 更好地使用 new MouseEvent(...)

标签: javascript mouseevent touch-event


【解决方案1】:

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

【讨论】:

  • 那么为什么每次第一次触摸都是一样的,然后是不同的,然后又是相同的,然后又是不同的?
  • 也许这会有所帮助? document.elementFromPoint(event.clientX, event.clientY);stackoverflow.com/questions/3918842/…
猜你喜欢
  • 2021-02-10
  • 1970-01-01
  • 2010-12-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-06-08
相关资源
最近更新 更多