Jquery: mousedown effect (while left click is held down)

拈花ヽ惹草 提交于 2019-11-26 20:46:24

I believe something like this would work:

var timeout, clicker = $('#clicker');

clicker.mousedown(function(){
    timeout = setInterval(function(){
        // Do something continuously 
    }, 500);

    return false;
});

$(document).mouseup(function(){
    clearInterval(timeout);
    return false;
});

See this demo: http://jsfiddle.net/8FmRd/

A small modification to the original answer:

$('#Clicker').mousedown(function () {
    //do something here
    timeout = setInterval(function () {
        //do same thing here again
    }, 500);

    return false;
});
$('#Clicker').mouseup(function () {
    clearInterval(timeout);
    return false;
});
$('#Clicker').mouseout(function () {
    clearInterval(timeout);
    return false;
});

With the mouseout event on the Clicker it stops when you move your mouse out of the click area.

The reason why I suggest to do the same thing twice is to get a smoother effect. If you don't do it once before the timeout is set it will be a delay of, in this case, 500ms before something happens.

Here's a pure JavaScript implementation of the supplied solutions which has extended support for touch screens. You supply the id, action to perform (function(){}) and the interval (ms) to repeat the action. Note that this implementation will also execute the action immediately, rather than waiting for the interval to lapse.

// Configures an element to execute a function periodically whilst it holds the user's attention via a mouse press and hold.
function assertPeriodicPress(id, action, interval) {
  // Listen for the MouseDown event.
  document.getElementById(id).addEventListener('mousedown', function(ev) { action(); timeout = setInterval(action, interval); return false; }, false);
  // Listen for mouse up events.
  document.getElementById(id).addEventListener('mouseup', function(ev) { clearInterval(timeout); return false; }, false);
  // Listen out for touch end events.
  document.getElementById(id).addEventListener('touchend', function(ev) { clearInterval(timeout); return false; }, false);
}
$.fn.click2=function(cb,interval){
   var timeout;
   if(!interval) interval=100;
   $(this).mousedown(function () { 
      var target=this;
       timeout = setInterval(function(){
          cb.apply(target);
       }, interval);

    return false;
   }).mouseup(function () {
      clearInterval(timeout);
      return false;
   }).mouseout(function () {
      clearInterval(timeout);
      return false;
   });
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!