【问题标题】:How to implement swipeRight and swipeLeft events in javascript如何在 javascript 中实现 swipeRight 和 swipeLeft 事件
【发布时间】:2014-06-16 15:41:59
【问题描述】:

这是我第一次在手机上实现应用程序。我正在使用javascripthtml 制作应用程序。

我想实现swipeRight and swipeLeft 事件。为此,我让大家建议使用jqueryhammer

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

使用 Jquery(不工作):

第1步:复制粘贴的代码表单this链接并保存文件并在html页面末尾提及。

第 2 步:运行以下代码

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

使用锤子(不工作):

第1步:复制粘贴的代码表单this链接并保存文件并在html页面末尾提及。

第 2 步:按照文档运行以下代码

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

在这种情况下,它会抛出异常,而页面加载时间本身。

例外:

Uncaught ReferenceError: Hammer is not defined 

我怎样才能达到我的要求。请任何人帮助我。

感谢和问候。

【问题讨论】:

  • 异常不是你贴的代码引起的。根本没有提到Hammer...
  • Hammer is not defined 错误提示 Hammer.js 在你使用该函数之前没有加载。

标签: javascript jquery swipe hammer.js


【解决方案1】:

在 Jquery 中的语法是

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

查看w3schools - 但您的代码看起来不错

为什么需要hammer.js?

查看 this link 并自己在 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>

【讨论】:

  • 这是否可以跨浏览器、在 Windows 触摸设备以及 iO 和 Android 上运行?
  • 没有苹果可以测试它。适用于安卓
猜你喜欢
  • 2013-03-14
  • 2012-08-25
  • 2014-10-02
  • 1970-01-01
  • 1970-01-01
  • 2014-07-02
  • 2015-03-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多