Que*_*ner 54 javascript touchscreen javascript-events
我正在使用与鼠标移动事件一起操作的YUI滑块.我想让它回应touchmove事件(iPhone和Android).当touchmove事件发生时,如何生成鼠标移动事件?我希望只是通过在顶部添加一些脚本,touchmove事件将被映射到鼠标移动事件,我将不必使用滑块更改任何内容.
Mic*_*ine 106
我相信这就是你想要的:
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);
}
Run Code Online (Sandbox Code Playgroud)
我已经捕获了触摸事件,然后手动触发我自己的鼠标事件来匹配.尽管代码不是特别通用的,但是应该适应大多数现有的拖放库以及可能是大多数现有的鼠标事件代码应该是微不足道的.希望这个想法对于为iPhone开发Web应用程序的人们来说会派上用场.
更新:
在发布此消息时,我注意到调用preventDefault所有触摸事件将阻止链接正常工作.打电话的主要原因preventDefault是阻止手机滚动,你可以通过回拨来调用它touchmove.这样做的唯一缺点是iPhone有时会在拖动原点上显示其悬停弹出窗口.如果我发现了一种防止这种情况的方法,我会更新这篇文章.
第二次更新:
我找到了关闭标注的CSS属性:-webkit-touch-callout.
我终于找到了一种使用 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);
}
Run Code Online (Sandbox Code Playgroud)
如果您看到“ filter_div”是我们有图表范围过滤器的图表区域,并且只有在该区域我们想要重写我们的触摸控件!
谢谢米奇。这是一个很好的解决方案。
| 归档时间: |
|
| 查看次数: |
83196 次 |
| 最近记录: |