滑块多次滑动

时间:2017-10-24 13:54:29

标签: javascript jquery

我正在尝试使用事件监听器touchstarttouchmove创建一个滑块。

如果单击按钮,滑块效果非常好。但是如果你从左到右移动手指,它会滑动很多次,直到最后一张图像,但它应该只滑动一次。你也不能向后滑。

var i = 0;

// Go next
$('.next').bind('click', function() {           
    niceSlider('left', '<');
});

// Go Back
$('.back').bind('click', function() {
    niceSlider('right', '>', 0); 
});

// Greather or less
function greatherOrLess(num1, operator, num2) {
    if (operator == '<') {
    return (num1 < num2) ? true : false;
  }
  else if (operator == '>') {
    return (num1 > num2) ? true : false;
  }
}

// Slider
function niceSlider(direction, operator, NumberOfAllImages = 4, position = 600) {
  var direction = (direction == 'left') ? '-' : '+';  
  if (greatherOrLess(i, operator, NumberOfAllImages)) {
    if (direction == '+' || direction == '-') {
      $('li').animate({'left': direction + '=600px'}, 300).delay(600);  
      x = (direction == '-') ? i++ : i--;
    }
  }
  console.log($('li:first').position().left);
  console.log(x);   
}

// Event Listener
var slider = document.querySelector('.slider');
slider.addEventListener('touchstart', handleTouchStart, false);
slider.addEventListener('touchmove', handleTouchMove, false);

// Start from touch
function handleTouchStart(evt) {
  startClientX = evt.touches[0].clientX;
  startClientY = evt.touches[0].clientY;
}

// Move from touch
function handleTouchMove(evt) {
  moveClientX = evt.touches[0].clientX;
  moveClientY = evt.touches[0].clientY;

  var diffClientX = startClientX - moveClientX;
  var diffClientY = startClientY - moveClientY;

  if (Math.abs(diffClientX) > Math.abs(diffClientY)) {
    if (diffClientX > 0) {
      niceSlider('left', '<');
    }
    else {
      niceSlider('right', '>');
    }
  }
}

函数handleTouchMove一定有问题。我该如何解决?

https://jsfiddle.net/6t1wx95f/16/

1 个答案:

答案 0 :(得分:1)

function handleTouchStart(evt) {
  startClientX = evt.touches[0].clientX;
  startClientY = evt.touches[0].clientY;
  checkTouch = true;
}

// Move from touch
function handleTouchMove(evt) {
  moveClientX = evt.touches[0].clientX;
  moveClientY = evt.touches[0].clientY;

  if (checkTouch) {
    var diffClientX = startClientX - moveClientX;
    var diffClientY = startClientY - moveClientY;
    if (Math.abs(diffClientX) > Math.abs(diffClientY)) {
      if (diffClientX > 0) {
        niceSlider('left', '<');
      } else {
        niceSlider('right', '>', 0);
      }
    }
    checkTouch = false;
  }
}

function handleTouchEnd(evt) {
  checkTouch = true;
}

这是jsFiddle,只检查一次使用布尔值。触摸移动下一个功能是每次移动都要求。