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

后端 未结 8 1577
天涯浪人
天涯浪人 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:40

    For cross platform developers:

    Mouseup/down seemed to work okay on android - but not all devices ie (samsung tab4). Did not work at all on iOS.

    Further research its seems that this is due to the element having selection and the native magnification interupts the listener.

    This event listener enables a thumbnail image to be opened in a bootstrap modal, if the user holds the image for 500ms.

    It uses a responsive image class therefore showing a larger version of the image. This piece of code has been fully tested upon (iPad/Tab4/TabA/Galaxy4):

    var pressTimer;  
    $(".thumbnail").on('touchend', function (e) {
       clearTimeout(pressTimer);
    }).on('touchstart', function (e) {
       var target = $(e.currentTarget);
       var imagePath = target.find('img').attr('src');
       var title = target.find('.myCaption:visible').first().text();
       $('#dds-modal-title').text(title);
       $('#dds-modal-img').attr('src', imagePath);
       // Set timeout
       pressTimer = window.setTimeout(function () {
          $('#dds-modal').modal('show');
       }, 500)
    });
    
    0 讨论(0)
  • 2020-11-27 04:40

    This better solution based on @Joshua, sometimes the code need to be called directly inside event (some web API require user acction to trigger something) for this case you can use this modification:

    var longtouch;
    var timer;
    //length of time we want the user to touch before we do something
    var touchduration = 500;
    
    function touchstart() {
        longtouch = false;
    
        timer = setTimeout(function() {
           longtouch = true;
           timer = null
        }, touchduration);
    }
    
    function touchend() {
        if (timer) {
            clearTimeout(timer);
            timer = null;
        }
        if (longtouch) {
            // your long acction inside event
            longtouch = false;
        }
    }
    

    in setTimeout you set the flag to true and inside touchend, you check if it was set.

    0 讨论(0)
提交回复
热议问题