简体   繁体   English

如何在没有大型图书馆的情况下获得触摸事件

[英]How do I get touch events without big library

I am using jquery, but I don't want to use jquery mobile, because it is so large, and I don't think I need it. 我正在使用jquery,但是我不想使用jquery mobile,因为它很大,而且我认为我不需要它。 All I am trying to do is get a touch event. 我要做的就是获得触摸事件。 This is what I've got. 这就是我所拥有的。

 $('#menuButton').on('click touchstart', function(){
  $('#menu').toggleClass('block')
 });

It only kind-of works, but seems to be firing twice a lot on my phone. 它仅能正常工作,但似乎在我的手机上多次触发两次。 I think I should check for both touchstart and touchend somehow. 我认为我应该以某种方式同时检查touchstart和touchend。 This needs to work on all types of devices, hopefully. 希望这可以在所有类型的设备上运行。 Thanks! 谢谢!

Behold! 看哪! The lifecycle of a touch: 触摸的生命周期:

  1. your finger hits the glass -> touchstart! 您的手指碰到了玻璃-> touchstart!
  2. your finger leaves the glass -> touchend! 你的手指离开玻璃杯->触摸!
  3. your finger it lingers -> click! 手指不停->单击!

Now the lifecycle of a mouse click: 现在单击鼠标的生命周期:

  1. your finger depresses the button -> mousedown! 您的手指按下按钮->按下鼠标!
  2. your finger it removes pressure from the button -> mouseup! 手指可以消除按钮上的压力-> mouseup!
  3. your finger it lingers -> click! 手指不停->单击!

If you are listening for both touchstart and click, the event will fire once on mouse or trackpad computers, and twice on touch devices as you are listening for 2 events in the lifecycle. 如果您同时监听触摸启动和单击,则在生命周期中监听2个事件时,该事件将在鼠标或触控板计算机上触发一次,在触摸设备上触发两次。

If you really want to use click for desktops and touchstart of touch devices (a good idea in many cases), you can do something like this: 如果您确实要在桌面和触摸设备的touchstart上使用click(在许多情况下是个好主意),则可以执行以下操作:

 var clickEvent = (isMobile)?'touchstart':'click';
 $('#menuButton').on(clickEvent, function(){
   $('#menu').toggleClass('block')
 });

How you go about finding isMobile is another story. 寻找isMobile是另一回事。


update : I've written a handy script for detecting mobile, if your interested its npm isMobile 更新:如果您感兴趣的npm isMobile ,我已经写了一个方便的脚本来检测移动设备

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

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