是否有一种更优雅的方法来检测触摸事件支持并分配一个“点击”或“;touchend"事件

Is there a more elegant way to detect touch events support and assign either a "click" or "touchend" event?

本文关键字:事件 一个 quot 分配 touchend 点击 触摸 一种 是否 检测 方法      更新时间:2023-09-26
var ClickOrTouchEvent = ("ontouchend" in document.documentElement ? "touchend" : "click");
$("#MyButton").on(ClickOrTouchEvent, function () {
  // Do something
});

这是可行的,但可能有一种更优雅的方法来检测触摸事件支持并分配"click"或"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和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();