使用Jquery在Ipad中进行Doubletap

时间:2015-08-01 10:08:09

标签: javascript jquery ios ipad

当我对我的内容进行双重打击时,我的任务是从ipad发出警报。我使用此代码检查我的双击

(function($){
// Determine if we on iPhone or iPad
var isiOS = false;
var agent = navigator.userAgent.toLowerCase();
if(agent.indexOf('iphone') >= 0 || agent.indexOf('ipad') >= 0){
       isiOS = true;
}

$.fn.doubletap = function(onDoubleTapCallback, onTapCallback, delay){
    var eventName, action;
    delay = delay == null? 500 : delay;
    eventName = isiOS == true? 'touchend' : 'click';

    $(this).bind(eventName, function(event){
        var now = new Date().getTime();
        var lastTouch = $(this).data('lastTouch') || now + 1 /** the first time this will make delta a negative number */;
        var delta = now - lastTouch;
        clearTimeout(action);
        if(delta<500 && delta>0){
            if(onDoubleTapCallback != null && typeof onDoubleTapCallback == 'function'){
                onDoubleTapCallback(event);
            }
        }else{
            $(this).data('lastTouch', now);
            action = setTimeout(function(evt){
                if(onTapCallback != null && typeof onTapCallback == 'function'){
                    onTapCallback(evt);
                }
                clearTimeout(action);   // clear the timeout
            }, delay, [event]);
        }
        $(this).data('lastTouch', now);
    });
};)(jQuery);

我从我的页面中调用此代码

$(".selector").doubletap(
/** doubletap-dblclick callback */
function(event){
    alert('double-tap');
},
/** touch-click callback (touch) */
function(event){
    alert('single-tap');
},
/** doubletap-dblclick delay (default is 500 ms) */
400);

它可以在我的桌面上运行。但是当我在ipad中打开它时它没有正常工作。请给我一些解决方案

1 个答案:

答案 0 :(得分:0)

最后我使用了这段代码。

var elm1 = document.getElementById('test1');
var elm2 = document.getElementById('test2');
var timeout;
var lastTap = 0;
elm1.addEventListener('touchend', function(event) {
var currentTime = new Date().getTime();
var tapLength = currentTime - lastTap;
clearTimeout(timeout);
if (tapLength < 500 && tapLength > 0) {
    elm2.innerHTML = 'Double Tap';
    event.preventDefault();
} else {
    elm2.innerHTML = 'Single Tap';
    timeout = setTimeout(function() {
        elm2.innerHTML = 'Single Tap (timeout)';
        clearTimeout(timeout);
    }, 500);
}
lastTap = currentTime;
});