jQuery连续mousedown

我有以下代码片段

$(document).mousedown(function(event) { doSomething(); } 

我可以成功捕获mousedown事件。

我正在尝试执行以下操作:

  1. 捕获第一个mousedown事件
  2. 我想检测用户是否仍然按住鼠标,以便我可以做其他事情。

就像是

 var mouseStillDown = false; $(document).mousedown(function(event) { mouseStillDown = true; doSomething(); }); function doSomething() { if (!mouseStillDown) { return; } // we could have come back from // SetInterval and the mouse is no longer down // do something if (mouseStillDown) { setInterval("doSomething", 100); } } $(document).mouseup(function(event) { mouseStillDown = false; }); 
 var int00; // declared here to make it visible to clearInterval. $('#trigger').mousedown(function(){ int00 = setInterval(function() { repeatingfunction(); }, 50); }).mouseup(function() { clearInterval(int00); }); function repeatingfunction() { // This will repeat // } 

您还可以在mouseleave事件上放置clearInterval

你实现了一些递归!

 var mouseisdown = false; $(document).mousedown(function(event) { mouseisdown = true; doSomething(); }).mouseup(function(event) { mouseisdown = false; }); function doSomething(){ //Code goes here if (mouseisdown) doSomething(); } 

您需要在mouseDown执行某些操作,开始执行某些操作并继续执行此操作直到mouseUp事件被触发。

使用mousedown事件设置标志,使用mouseup取消设置标志。 然后你可以简单地检查标志,看看它是否已设置。

〔实施例

 var mouseDownFlag = false; $(document).mousedown(function(event) { mouseDownFlag = true; someFunc(); } $(document).mouseup(function(event) { mouseUpFlag = true; } var someFunc = function(){ if(mouseDownFLag){//only run this function when the mouse is clicked // your code setTimeout("somefunc()", 1000); //run this function once per second if your mouse is down. } } 

希望有所帮助!

 $(document).ready(function(){ var mouseStillDown = false; $('#some_element').mousedown(function() { do_something(); }).mouseup(function() { clearInterval(mouseStillDown); mouseStillDown = false; }); function do_something() { // add some code here that repeats while mouse down if (!mouseStillDown) { mouseStillDown = setInterval(do_something, 100); } } });