JavaScript将触摸事件映射到鼠标事件

我正在使用与鼠标移动事件一起操作的YUI滑块。我想让它响应touchmove事件(iPhone和Android)。发生touchmove事件时如何产生鼠标移动事件?我希望仅在顶部添加一些脚本,即可将touchmove事件映射到鼠标移动事件,而无需使用滑块进行任何更改。



慕的地10843
浏览 872回答 3
3回答

红颜莎娜

我确定这是您想要的: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);    }我已经捕获了触摸事件,然后手动触发了自己的鼠标事件以进行匹配。尽管该代码并不是特别通用,但要适应大多数现有的拖放库,甚至可能是大多数现有的鼠标事件代码,都应该是微不足道的。希望这个想法对开发用于iPhone的Web应用程序的人有用。更新:在发布此内容时,我注意到调用preventDefault所有触摸事件将阻止链接正常工作。preventDefault根本不打电话的主要原因是停止手机滚动,您可以通过仅在touchmove回叫上拨打电话来做到这一点。这样做的唯一缺点是,iPhone有时会在拖动原点上方显示其悬停弹出窗口。如果我发现了一种防止这种情况的方法,我将更新这篇文章。第二次更新:我发现CSS属性可以关闭标注:-webkit-touch-callout。

牛魔王的故事

对于将来的用户,可以在这里回来使用以下代码:var eventMap = {};(function(){var eventReplacement = {    "mousedown": ["touchstart mousedown", "mousedown"],    "mouseup": ["touchend mouseup", "mouseup"],    "click": ["touchstart click", "click"],    "mousemove": ["touchmove mousemove", "mousemove"]};for (i in eventReplacement) {    if (typeof window["on" + eventReplacement[i][0]] == "object") {        eventMap[i] = eventReplacement[i][0];    }     else {        eventMap[i] = eventReplacement[i][1];    }; };})();然后在事件中使用如下所示:$(".yourDiv").on(eventMap.mouseup, function(event) {      //your code}

达令说

我终于找到了一种使用Mickey的解决方案而不是他的init函数来使其工作的方法。在这里使用init函数。function init() {    document.getElementById('filter_div').addEventListener("touchstart", touchHandler, true);    document.getElementById('filter_div').addEventListener("touchmove", touchHandler, true);    document.getElementById('filter_div').addEventListener("touchend", touchHandler, true);    document.getElementById('filter_div').addEventListener("touchcancel", touchHandler, true);}如果您看到“ filter_div”是我们拥有图表范围过滤器的图表区域,并且仅在该区域中我们要重写我们的触摸控件!谢谢米奇。这是一个很好的解决方案。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript