繁体   English   中英

JS使用mousemove或touchmove

[英]JS use mousemove or touchmove

我想知道如何根据使用哪个设备的应用程序来使用mousemove或touchmove。 我希望启用触摸功能的设备可以收听touchmove,而希望台式设备使用mousemove。 我也想使用在移动设备上似乎缺少的offsetX和offsetY = /

您可以将事件包装在一个对象中,并根据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;
  }

  // ...
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM