简体   繁体   English

带触摸功能的滑块

[英]Slider with touch function

I have created a simple slider. 我创建了一个简单的滑块。 I want it also for smartphones and not only for desktops. 我也希望将其用于智能手机,而不仅是台式机。 So in this case it should be possible to let it slide when you move your finger from left to right or from right to left. 因此,在这种情况下,当您从左向右或从右向左移动手指时,应该可以使其滑动。 For now it only works when you click on buttons. 目前,它仅在单击按钮时才有效。

I have no idea how to start with it. 我不知道如何开始。 How can I do this? 我怎样才能做到这一点?

var i = 0;
$('.next').bind('click', function() {           
  if (i < 4) {      
        $('li').animate({'left': '-=600px'}, 300).delay(600);  
    i++;
  }
  console.log($('li:first').position().left);
  console.log(i);
});

$('.back').bind('click', function() {
    if (i > 0) {
    if ($('li:first').position().left < 0) {    
      $('li').animate({'left': '+=600px'}, 300).delay(600);
      i--;
    }
  }
  console.log(i);
});

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

PS: It should work without using a plugin. PS:它应该不使用插件就可以工作。

I updated your fiddle: https://jsfiddle.net/6t1wx95f/13/ 我更新了您的小提琴: https : //jsfiddle.net/6t1wx95f/13/

Tested in chrome (in responsive view to have the touch events working). 经过chrome测试(在响应式视图中,触摸事件有效)。 Credit goes to this answer . 这个答案值得赞扬

Basically, you just need to use touchstart and touchmove events. 基本上,您只需要使用touchstarttouchmove事件。 When you touchmove you just take your X position and compare it to where it was when touch-started. 触摸移动时,您只需将X位置与触摸开始时的位置进行比较即可。

See the touch events docs. 请参阅触摸事件文档。 It's all in vanilla javascript so you won't have to include any plugin. 全部使用香草javascript,因此您无需包括任何插件。

// Set up events
var slider = document.getElementsByClassName('slider')[0];
slider.addEventListener('touchstart', handleTouchStart, false);        
slider.addEventListener('touchmove', handleTouchMove, false);

..and ..和

if ( xDiff > 0 ) {
    /* left swipe */ 
    slideRight();
} else {
    /* right swipe */
    slideLeft();
} 

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

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