2017-05-05 36 views
0

我是新来的移动触摸事件。 我试图让这个代码也可以在手机上工作,但我害怕我只是在浪费我的时间。我不想添加某种图书馆,只是香草JavaScript。如何让mousemove进入touchmove?

它是我在div中移动的路线图。

有什么提示吗?

最好的问候, 基督教

function startDrag(e) { 
      // determine event object 
      if (!e) { 
       var e = window.event; 
      } 

       if(e.preventDefault) e.preventDefault(); 


      // IE uses srcElement, others use target 
      targ = e.target ? e.target : e.srcElement; 

      if (targ.className != 'roadmap') {return}; 
      // calculate event X, Y coordinates 
       offsetX = e.clientX; 
       offsetY = e.clientY; 

      // assign default values for top and left properties 
      if (!targ.style.left) { targ.style.left='-140px'}; 
      if (!targ.style.top) { targ.style.top='-300px'}; 

      // calculate integer values for top and left 
      // properties 
      coordX = parseInt(targ.style.left); 
      coordY = parseInt(targ.style.top); 
      drag = true; 

      // move div element 
       document.ontouchmove=dragDiv; 
      return false; 

     } 
     function dragDiv(e) { 
      if (!drag) {return}; 
      if (!e) { var e= window.event}; 

      // target 
      console.log(e.target) 
      var t = e.target, 
        img = t, 
        parent = img.parentElement, 
        imgWidth = img.clientWidth, 
        imgHeight = img.clientHeight; 

      // maxes 
      var y = coordY+e.clientY-offsetY, 
        x = coordX+e.clientX-offsetX; 

      // set boundies 
      if (parent.clientHeight == null) { 
       parent.clientHeight = 1; 
       targ.style.left=1+'px'; 
      } 
      var imgBottom = parent.clientHeight-imgHeight 
        imgRight = parent.clientWidth-imgWidth; 

      // stop drag on overflow 
      if ( // left 
         /^-\d+$/.test(y) && 
         // // top 
         /^-\d+$/.test(x) && 
         // // bottom 
         imgBottom < y && 
         // // bottom 
         imgRight < x 
         ) { 

       targ.style.left=coordX+e.clientX-offsetX+'px'; 
       targ.style.top=coordY+e.clientY-offsetY+'px'; 

      }; 
      return false; 
     } 
     function stopDrag() { 
      drag=false; 
     } 


     window.onload = function() { 
      document.onmousedown = startDrag; 
      document.onmouseup = stopDrag; 

      // mobile 
      document.addEventListener("touchmove", startDrag, false); 
      document.addEventListener("touchend", stopDrag, false); 
     } 
+0

阅读触摸API https://developer.mozilla.org/en-US/docs/Web/API/Touch_events –

回答

0

尝试使用,而不是 'touchmove' 的 'touchstart' 事件:

document.addEventListener("touchstart", startDrag, false); 
document.addEventListener("touchend", stopDrag, false); 

然后设置你的 'OFFSETX' 和 'OFFSETY' 变量要么使用鼠标或触摸坐标:

offsetX = e.clientX || e.touches[0].clientX; 
offsetY = e.clientY || e.touches[0].clientY; 

希望这有助于。

+0

谢谢。更进一步:-) 似乎我没有达到dragDiv功能。任何想法? document.ontouchstart = dragDiv; –