[Front-End] mouseDown手機上運行

前言

手機上無法使用mouseDown等等的事件,必須使用touchStart,網路上找到別人寫的替換方法。

程式碼

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
var mouseEventTypes = {
touchstart : "mousedown",
touchmove : "mousemove",
touchend : "mouseup"
};
for (originalType in mouseEventTypes) {
document.addEventListener(originalType, function(originalEvent) {
event = document.createEvent("MouseEvents");
touch = originalEvent.changedTouches[0];
event.initMouseEvent(mouseEventTypes[originalEvent.type], true, true,
window, 0, touch.screenX, touch.screenY, touch.clientX,
touch.clientY, touch.ctrlKey, touch.altKey, touch.shiftKey,
touch.metaKey, 0, null);
originalEvent.target.dispatchEvent(event);
});
}