[英]Is there a more elegant way to detect touch events support and assign either a “click” or “touchend” event?
var ClickOrTouchEvent = ("ontouchend" in document.documentElement ? "touchend" : "click");
$("#MyButton").on(ClickOrTouchEvent, function () {
// Do something
});
这有效,但可能有一种更优雅的方式来检测触摸事件支持并分配“点击”或“touchend”事件。
人们已经创建了许多插件来为基于jquery的Web应用程序(如拖放)添加更高级的触摸支持。 您可以使用其中一种而不是尝试制作自己的。
这说他们在我的经历中似乎都有他们奇怪的问题,所以你可能需要调整。 看起来您的解决方案与他们的大多数解决方案属于同一个系列。 以下是一些流行的插件以及他们用于决定触摸或点击的解决方案:
TouchPunch为所有内容增添了触感:
// Detect touch support and save it in support
$.support.touch = 'ontouchend' in document;
// Ignore browsers without touch support
if (!$.support.touch) {
return;
}
//rest of plugin code follows
jquery-ui-for-ipad-and-iphone有一个方法你必须调用才能将触摸事件添加到所需的元素......但仅限于浏览器支持它。
// Same deal. Detect touch support and save it in support
$.extend($.support, {
touch: "ontouchend" in document
});
//
// Hook up touch events
//
$.fn.addTouch = function() {
if ($.support.touch) {
this.each(function(i,el){
el.addEventListener("touchstart", iPadTouchHandler, false);
el.addEventListener("touchmove", iPadTouchHandler, false);
el.addEventListener("touchend", iPadTouchHandler, false);
el.addEventListener("touchcancel", iPadTouchHandler, false);
});
}
};
....
然后在应用了jQuery UI函数的元素上调用addTouch:
$('Element').dialog().addTouch();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.