我开发了一种拖放应用程序,用于在足球游戏中记录统计数据,该程序在桌面上可以完美运行。但是,我的下一个挑战是,我需要它与手机/ ipad兼容。因此,我需要使用Javascript将触摸事件映射到鼠标事件,但是我不确定如何做到这一点。
此代码处理拖动事件:
function drag_start(event) {
_('app_status').innerHTML = "Dragging the "+event.target.getAttribute('name');
event.dataTransfer.dropEffect = "move";
event.dataTransfer.setData("text", event.target.getAttribute('id') );
}
function drag_enter(event) {
_('app_status').innerHTML = "You are dragging over the "+event.target.getAttribute('name');
}
function drag_leave(event) {
_('app_status').innerHTML = "You left the "+event.target.getAttribute('name');
}
function drag_end(event) {
if(droppedIn == false){
_('app_status').innerHTML = "You let the "+event.target.getAttribute('name')+" go.";
}
droppedIn = false;
}
我已尝试根据此问题JavaScript mapping touch events to mouse events
添加此代码 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);
}
任何帮助都非常感激:)