JS使用mousemove或touchmove

时间:2014-03-15 12:34:58

标签: javascript

我想知道如何使用mousemove或touchmove,具体取决于使用该应用程序的设备。我希望支持触摸的设备能够收听touchmove和桌面设备,以便使用mousemove。我还想使用在移动设备上似乎缺少的offsetX和offsetY = /

1 个答案:

答案 0 :(得分:2)

您可以将事件包装在一个对象中,并根据is_touch_supported:

进行设置
var body = document.querySelector('body'),
    is_touch_supported = ('ontouchstart' in window) ? true : false,
    EVENTS = {
      POINTER_DOWN : is_touch_supported ? 'touchstart' : 'mousedown',
      POINTER_UP   : is_touch_supported ? 'touchend'   : 'mouseup',
      POINTER_MOVE : is_touch_supported ? 'touchmove'  : 'mousemove'
    };

现在你可以使用这样的事件:

body.addEventListener(EVENTS.POINTER_MOVE, function (e) {
  e.preventDefault();

  // normalize event so you can use e.offset X/Y
  if(is_touch_supported){
    e = e.changedTouches[0];
    e.offsetX = e.pageX - e.target.offsetLeft;
    e.offsetY = e.pageY - e.target.offsetTop;
  }

  // ...
});
相关问题