当当前的x坐标和开始的x坐标不同时,是否有一种方法可以每隔x毫秒获取一次touchmove事件中的触摸位置,然后执行一个函数。 50px?

谢谢

最佳答案

请尝试以下方法;



$('document').ready(function() {

  var touch,
    action,
    diffX,
    diffY,
    endX,
    endY,
    startX,
    startY,
    timer,
    timerXseconds = 500, // Change to the Time(milliseconds) to check for touch position
    xDifferenceX = 50, // Change to difference (px) for x-coordinates from starting point to run your function
    xDifferenceY = 50; // Change to difference (px) for y-coordinates from starting point

  function getCoord(e, c) {
    return /touch/.test(e.type) ? (e.originalEvent || e).changedTouches[0]['page' + c] : e['page' + c];
  }

  function testTouch(e) {
    if (e.type == 'touchstart') {
      touch = true;
    } else if (touch) {
      touch = false;
      return false;
    }
    return true;
  }

  function onStart(ev) {
    if (testTouch(ev) && !action) {
      action = true;
      startX = getCoord(ev, 'X');
      startY = getCoord(ev, 'Y');
      diffX = 0;
      diffY = 0;
      timer = window.setInterval(checkPosition(ev), timerXseconds); // get coordinaties ever X time
      if (ev.type == 'mousedown') {
        $(document).on('mousemove', onMove).on('mouseup', onEnd);
      }

    }
  }

  function onMove(ev) {
    if (action) {
      checkPosition(ev)
    }
  }

  function checkPosition(ev) {
    endX = getCoord(ev, 'X');
    endY = getCoord(ev, 'Y');
    diffX = endX - startX;
    diffY = endY - startY;
    // Check if coordinates on Move are Different than Starting point by X pixels
    if (Math.abs(diffX) > xDifferenceX || Math.abs(diffY) > xDifferenceY) {
    //  console.log('Start is :' + startX + ' End is : ' + endX + 'Difference is : ' + diffX);
      $(this).trigger('touchend');

      // here Add your function to run...
    }

  }

  function onEnd(ev) {
    window.clearInterval(timer);
    if (action) {
      action = false;
      if (ev.type == 'mouseup') {
        $(document).off('mousemove', onMove).off('mouseup', onEnd);
      }
    }
  }

  $('#monitor')
    .bind('touchstart mousedown', onStart)
    .bind('touchmove', onMove)
    .bind('touchend touchcancel', onEnd);
});

body {
  margin: 0;
  padding: 0;
}
#monitor {
  height: 500px;
  width: 500px;
  position: relative;
  display: block;
  left: 50px;
  top: 50px;
  background: green;
}
.box {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  text-align: center;
  font-weight: bold;
  bottom: 0;
  background: white;
  width: 50px;
  height: 50px;
  margin: auto;
  font-size: 16px;
  line-height: 23px;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id='monitor'>
  <div class='box'>start here</div>
</div>





阅读此post以获得更详细的答案

09-11 07:02