是否有更优雅的方式来检测触摸事件支持并分配“点击”或“touchend”事件?

时间:2013-01-10 21:29:27

标签: javascript jquery touch

var ClickOrTouchEvent = ("ontouchend" in document.documentElement ? "touchend" : "click");

$("#MyButton").on(ClickOrTouchEvent, function () {
  // Do something
});

这样可行,但可能有更优雅的方式来检测触摸事件支持并分配“点击”或“touchend”事件。

1 个答案:

答案 0 :(得分:3)

人们已经创建了许多插件来为基于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();