一个糟糕但快速的解决方法是将触摸事件映射到里程表上的鼠标。取自https://stackoverflow.com/a/1781750/3946520
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;
}
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 mapTouchToMouse(elem)
{
elem.addEventListener("touchstart", touchHandler, true);
elem.addEventListener("touchmove", touchHandler, true);
elem.addEventListener("touchend", touchHandler, true);
elem.addEventListener("touchcancel", touchHandler, true);
}
mapTouchToMouse(document.getElementById("p1-odometer"));
mapTouchToMouse(document.getElementById("p2-odometer"));
还要使其在边缘和 IE 上工作,将样式属性 touch-action: none; -ms-touch-action:none; 添加到您的 SVG 元素:
<svg id="p2-odometer" width="100%" viewBox="-26 -26 57 52" background="#eee" style="touch-action:none; -ms-touch-action:none;">
<svg id="p1-odometer" width="100%" viewBox="-26 -26 57 52" background="#eee" style="touch-action:none; -ms-touch-action:none;">
此外,您不必将 touch-punch jquery-ui 扩展加载到页面即可使用此方法。
如果您不想要这种方法并且想要通过自定义触摸处理,那么您需要使用这些事件:'touchstart', 'touchmove', 'touchend', 'touchcancel' 代替 'mousedown', 'mousemove', 'mouseup', 'mouseleave'。并对这些事件的处理函数进行相应的更改。我希望这会有所帮助。