How to detect a long press on a div in Jquery?

前端 未结 12 1406
广开言路
广开言路 2020-12-08 04:44

I would like to execute some function when the user presses for 2 seconds on a div.

Is it possible ?

Here is my code to detect the click on the

12条回答
  •  臣服心动
    2020-12-08 05:03

    Simple. No need for long uneccesary coding.

    (function(){
        // how many milliseconds is a long press?
        var offset = 500;
    
        $(".button").on('mousedown', function(e){
            // holds the start time
            $(this).data('start',new Date().getTime());
            $(this).addClass("selected");
        }).on('mouseup', function(e){
            if (new Date().getTime() >= ($(this).data('start') + offset)){
                //alert('ur click lasted for over 2 secs');
                $(this).addClass("selected");
            }else{
                $(this).removeClass("selected");
            }
        }).on('mouseleave', function(e){
            start = 0;
            //you can add destroy lingering functions on mouse leave
        });
    
    }());
    

    http://jsfiddle.net/donddoug/8D4nJ/

提交回复
热议问题