删除Android的webapps的onclick延迟

时间:2012-03-15 14:38:30

标签: javascript android touch ontouchevent

您好我正在构建一个webapp。要删除onclick延迟,我发现了这个脚本 http://cubiq.org/remove-onclick-delay-on-webkit-for-iphone 代码基本上是 -

function NoClickDelay(el) {
this.element = el;
if( 'ontouchstart' in window ){  
    console.log("===================touch supported :P")
    this.element.addEventListener('touchstart', this.handleEvent, false);
}                              
}

NoClickDelay.prototype = {
handleEvent: function(e) {
     switch(e.type) {
        case 'touchstart': this.onTouchStart(e); break;
        case 'touchmove': this.onTouchMove(e); break;
        case 'touchend': this.onTouchEnd(e); break;
    }
},

onTouchStart: function(e) {

    //e.preventDefault(); //removed to let the page scroll
    this.moved = false;

    this.element.addEventListener('touchmove', this, false);
    this.element.addEventListener('touchend', this, false);
},

onTouchMove: function(e) {

    this.moved = true;
},

onTouchEnd: function(e) {
    this.element.removeEventListener('touchmove', this, false);
    this.element.removeEventListener('touchend', this, false);

    if( !this.moved ) {
        // Place your code here or use the click simulation below
        var theTarget = document.elementFromPoint(e.changedTouches[0].clientX, e.changedTouches[0].clientY);
        if(theTarget.nodeType == 3) theTarget = theTarget.parentNode;

        var theEvent = document.createEvent('MouseEvents');
        theEvent.initEvent('click', true, true);
        theTarget.dispatchEvent(theEvent);
    }
}
};

我的问题是,这适用于iphone / ipad但不适用于Android。什么阻止它在Android中工作,我该怎么做才能在Android和其他设备中实现类似的行为?请帮忙。

4 个答案:

答案 0 :(得分:3)

我们遇到了同样的问题,并以稍微不同的方式解决了这个问题。 我们能够为iPhone和Android修复它。点击将立即触发,延迟事件将被忽略。也许你可以使用它:

https://github.com/cargomedia/jquery.touchToClick

答案 1 :(得分:1)

在您的链接中有人评论Android解决方案(我还没试过):

Android与laggy onClicks有同样的问题。你的演示在Android上不起作用,除非我注释掉window.Touch下面,所以我相信DOM属性只在iOS上可见。

function NoClickDelay(el) {
this.element = el;
// if (window.Touch) not available on android
this.element.addEventListener(‘touchstart’, this, false);
}

通过上述更改,Android获得了非延迟触摸事件!

答案 2 :(得分:0)

touchToClick或fastclick在我的情况下不起作用。

我在onclick事件中有很多代码,我实际上正在使用Tappy:

onClick event in android webview too slow

答案 3 :(得分:0)

<meta name="viewport" content="width=device-width, user-scalable=no">

这会禁用双击缩放,因此浏览器不会等待检测到双击。无需担心点击事件。可悲的是,它仅适用于最近的浏览器。