繁体   English   中英

如何在JavaScript中实现swipeRight和swipeLeft事件

[英]How to implement swipeRight and swipeLeft events in javascript

这是我第一次在移动设备中实现应用程序。我正在使用javascripthtml制作应用程序。

我想要实现swipeRight and swipeLeft events.For这个我瞪大眼睛大家建议为使用jqueryhammer

我尝试了两个插件,两个插件都失败了。

使用Jquery(不起作用):

步骤1:通过链接复制粘贴的代码,然后保存文件并在html页面末尾提及。

步骤2:运行以下代码

  $('#eleId').on('swiperight',function(){alert("swipeRight");})

使用锤子(不起作用):

步骤1:通过链接复制粘贴的代码,然后保存文件并在html页面末尾提及。

步骤2:根据文档运行以下代码

  $('#eleId').on('swipe',function(){alert("swipeRight");})

在这种情况下,页面加载时间本身会引发异常。

例外情况:

Uncaught ReferenceError: Hammer is not defined 

我如何达到我的要求。请任何人帮助我。

谢谢并恭祝安康。

在Jquery中,语法为

 $("selector").on("swipeleft",function(event){...})

查看w3schools-但是您的代码看起来正确

你为什么需要hammer.js?

签出此链接,并使用javascript自己构建滑动事件。

(以防万一链接被删除,这里是代码)

<script>



 window.addEventListener('load', function(){

   var touchsurface = document.getElementById('touchsurface'),
  startX,
  startY,
  dist,
  threshold = 150, //required min distance traveled to be considered swipe
  allowedTime = 200, // maximum time allowed to travel that distance
  elapsedTime,
  startTime

 function handleswipe(isrightswipe){
  if (isrightswipe)
   touchsurface.innerHTML = 'Congrats, you\'ve made a <span style="color:red">right swipe!</span>'
  else{
   touchsurface.innerHTML = 'Condition for right swipe not met yet'
  }
 }

 touchsurface.addEventListener('touchstart', function(e){
  touchsurface.innerHTML = ''
  var touchobj = e.changedTouches[0]
  dist = 0
  startX = touchobj.pageX
  startY = touchobj.pageY
  startTime = new Date().getTime() // record time when finger first makes contact with surface
  e.preventDefault()

 }, false)

 touchsurface.addEventListener('touchmove', function(e){
  e.preventDefault() // prevent scrolling when inside DIV
 }, false)

 touchsurface.addEventListener('touchend', function(e){
  var touchobj = e.changedTouches[0]
  dist = touchobj.pageX - startX // get total dist traveled by finger while in contact with surface
  elapsedTime = new Date().getTime() - startTime // get time elapsed
  // check that elapsed time is within specified, horizontal dist traveled >= threshold, and vertical dist traveled <= 100
var swiperightBol = (elapsedTime <= allowedTime && dist >= threshold && Math.abs(touchobj.pageY - startY) <= 100)
handleswipe(swiperightBol)
e.preventDefault()
}, false)

}, false)

</script>

<div id="touchsurface">Swipe Me</div>

暂无
暂无

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

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