Jquery:mousedown效果(按下左键时)

时间:2010-10-20 11:04:15

标签: javascript jquery mouse click

我需要一个在按下按钮时执行功能的功能,并在按下按钮时停止执行

$('#button').--while being held down--(function() {
     //execute continuously
}); 

4 个答案:

答案 0 :(得分:52)

我相信这样的事情会起作用:

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

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

    return false;
});

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

查看此演示:http://jsfiddle.net/8FmRd/

答案 1 :(得分:18)

对原始答案的一个小修改:

$('#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;
});

使用Clicker上的mouseout事件,当您将鼠标移出点击区域时,它会停止。

我建议两次做同样的事情的原因是为了获得更平滑的效果。如果你在设置超时之前没有做过一次,那么在发生这种情况之前,这将延迟500ms。

答案 2 :(得分:2)

这是所提供解决方案的纯JavaScript实现,扩展了对触摸屏的支持。您提供idaction执行(function(){})和interval(ms)重复action。请注意,此实现也会立即执行action,而不是等待interval失效。

// 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);
}

答案 3 :(得分:1)

$.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;
   });
}
相关问题