鼠标按住时JavaScript重复操作

Bri*_*ian 17 javascript jquery

是否有一个JavaScript函数重复每隔这么多毫秒按下一个html按钮?如果可以使用标准JavaScript完成它会很棒,但使用jQuery或jQuery插件也会很棒.

cle*_*tus 27

在该mousedown()事件上,此代码启动重复计时器(在此示例中每500毫秒),一旦mouseup()事件发生就会被取消.这应该适合你想要的:

var intervalId;
$("#button").mousedown(function() {
  intervalId = setInterval(do_something, 500);
}).mouseup(function() {
  clearInterval(intervalId);
});

function do_something() {
  // whatever
}
Run Code Online (Sandbox Code Playgroud)

有关setInterval()清除计时器的更多信息,请参阅.

  • 如果你希望事件立即发生,AND每500毫秒,只需在调用setInterval之前立即调用`do_something()`. (2认同)

mun*_*nch 6

我会setInterval()在一个函数中使用javascript函数,该函数在鼠标按下时被调用.

<input type="button" id="button" onmousedown="inter=setInterval(startAction, 1*1000);"
onmouseup="clearInterval(inter);" value="click here" />

<script type="text/javascript">
    function startAction(){
        //whatever you want done
    }
</script>
Run Code Online (Sandbox Code Playgroud)


小智 6

我发现上面列出的两种解决方案都有问题。

onmouseup仅当鼠标在按钮上方时被释放时才会触发。如果用户按住鼠标,然后在释放鼠标之前将鼠标移开,则clearInterval永远不会触发,因此do_something将永远触发。

您需要添加另一个事件“ onmouseout”,它也调用clearInterval.

  • 是的,但请通过添加示例代码使其成为完整的答案。 (2认同)

小智 5

var intervalId;
$("#button").mousedown(function() {
  intervalId = setInterval(do_something, 500);
}).mouseup(function() {
  clearInterval(intervalId);
}).mouseleave(function() {
//this should help solve the problem that occurs when the mouse leaves the button while pressed down
  clearInterval(intervalId);
});

function do_something() {
  // whatever
}
Run Code Online (Sandbox Code Playgroud)