How can I listen for a click-and-hold in jQuery?

2019-01-03 12:19发布

I want to be able to fire an event when a user clicks on a button, then holds that click down for 1000 to 1500 ms.

Is there jQuery core functionality or a plugin that already enables this?

Should I roll my own? Where should I start?

8条回答
姐就是有狂的资本
2楼-- · 2019-01-03 12:55
var timeoutId = 0;

$('#myElement').on('mousedown', function() {
    timeoutId = setTimeout(myFunction, 1000);
}).on('mouseup mouseleave', function() {
    clearTimeout(timeoutId);
});

Edit: correction per AndyE...thanks!

Edit 2: using bind now for two events with same handler per gnarf

查看更多
萌系小妹纸
3楼-- · 2019-01-03 12:55
    var _timeoutId = 0;

    var _startHoldEvent = function(e) {
      _timeoutId = setInterval(function() {
         myFunction.call(e.target);
      }, 1000);
    };

    var _stopHoldEvent = function() {
      clearInterval(_timeoutId );
    };

    $('#myElement').on('mousedown', _startHoldEvent).on('mouseup mouseleave', _stopHoldEvent);
查看更多
登录 后发表回答