简体   繁体   English

向左/向右滑动即可浏览网页

[英]Swipe left/right for a webpage

I have a series of enumerated webpages, and at the moment I have a left and a right arrow icon on each page to navigate to the previous/next page in the series. 我有一系列枚举的网页,此刻,我在每个页面上都有向左和向右箭头图标,以导航到该系列中的上一页/下一页。

My question: What is the simplest (!) way to implement swipe left/right gesture to do the same? 我的问题:实现左右滑动手势以执行相同操作的最简单(!)方法是什么? (No other gestures--no complex solutions please, I am a bloody newbie!) (没有其他手势,请没有复杂的解决方案,我是个流血的新手!)

Thank you very much in advance for your answers! 预先非常感谢您的回答!

Simply store the first point the user touched down: 只需存储用户触及的第一点:

 var start = null;
 window.addEventListener("touchstart",function(event){
   if(event.touches.length === 1){
      //just one finger touched
      start = event.touches.item(0).clientX;
    }else{
      //a second finger hit the screen, abort the touch
      start = null;
    }
  });

Then if the finger lefts the screen, check if the offset is higher then a value: 然后,如果手指离开屏幕,请检查偏移量是否高于某个值:

 window.addEventListener("touchend",function(event){
    var offset = 100;//at least 100px are a swipe
    if(start){
      //the only finger that hit the screen left it
      var end = event.changedTouches.item(0).clientX;

      if(end > start + offset){
       //a left -> right swipe
      }
      if(end < start - offset ){
       //a right -> left swipe
      }
    }
  });

You might add additional checks eg if the delta y ( clientY) stays under a certain amount, or if the touchmove just goes in one direction. 您可能会添加其他检查,例如,增量(clientY)是否保持在一定数量以下,或者触摸移动是否只是朝一个方向移动。 However thats optional and depends if you need to differ it from another swipe action. 但是,那是可选的,取决于您是否需要将其与另一个滑动操作区分开。 You could also make the needed swipe dependend off the pages width, eg: 您还可以使所需的滑动依赖于页面宽度,例如:

var offset = window.clientX * 0.9; // the swipe mist be 90% of the windows size

Test it 测试一下

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

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