我正在使用与鼠标移动事件一起操作的 YUI 滑块。我想让它响应touchmove
事件(iPhone 和 Android)。事件发生时如何产生鼠标移动事件touchmove
?我希望只需在顶部添加一些脚本,touchmove
事件就会映射到鼠标移动事件,而我不必使用滑块进行任何更改。
5 回答
我相信这就是你想要的:
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
.
我终于找到了一种使用 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
' 是我们拥有图表范围过滤器的图表区域,并且只有在该区域中,我们才想重写我们的触摸控件!
谢谢你米奇。这是一个很好的解决方案。
按照@Mickey Shine 的回答,Touch Punch提供了触摸事件到点击事件的映射。它的构建是为了将这种支持放入 jQuery UI,但代码信息量很大。
对于回来这里的未来用户,可能会使用以下代码:
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 的代码在 Edge 和 Internet Explorer 上运行,请在您希望进行模拟的元素的 .css 中添加以下行:
.areaWhereSimulationHappens {
overflow: hidden;
touch-action: none;
-ms-touch-action: none;
}
这些行阻止了边缘和 IE 的默认触摸。但是,如果您将其添加到错误的元素,那么它也会禁用滚动(默认情况下会在边缘和触摸设备上的 IE 上发生)。