[英]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:
触摸的生命周期:
Now the lifecycle of a mouse 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.