How to detect a long touch pressure with javascript for android and iphone?

后端 未结 8 1659
天涯浪人
天涯浪人 2020-11-27 04:05

How to detect a long touch pressure with javascript for android and iphone? native javascript or jquery...

I want something that sound like :



        
8条回答
  •  孤城傲影
    2020-11-27 04:35

    Here is an extended version of Joshua answer, as his code works well till user doesn't perform multitouch (you can tap screen with two fingers and function will be triggered two times, 4 fingers - 4 times). After some additional test scenarios I even triggered possibility to touch very freequently and receive function executing after each tap.

    I added variable named 'lockTimer' which should lock any additional touchstarts before user trigger 'touchend'.

    var onlongtouch; 
    var timer;
    var touchduration = 800; //length of time we want the user to touch before we do something
    
    function touchstart(e) {
        e.preventDefault();
        if (!timer) {
            timer = setTimeout(onlongtouch, touchduration);
        }
    }
    
    function touchend() {
        //stops short touches from firing the event
        if (timer) {
            clearTimeout(timer);
            timer = null;
        }
    }
    
    onlongtouch = function() { 
        timer = null;
        document.getElementById('ping').innerText+='ping\n'; 
    };
    
    document.addEventListener("DOMContentLoaded", function(event) { 
        window.addEventListener("touchstart", touchstart, false);
        window.addEventListener("touchend", touchend, false);
    });

提交回复
热议问题