简体   繁体   English

按住鼠标时 JavaScript 重复动作

[英]JavaScript repeat action when mouse held down

Is there to have a JavaScript function repeated every so many milliseconds that an html button is held down?是否有一个 JavaScript 函数每隔这么多毫秒重复一次,以至于按住 html 按钮? It would be great if this could be done with standard JavaScript, but using jQuery or a jQuery plugin would be great too.如果这可以用标准 JavaScript 完成就太好了,但使用 jQuery 或 jQuery 插件也很棒。

On the mousedown() event, this code starts a repeating timer (every 500ms in this example) that is cancelled as soon as the mouseup() event occurs.mousedown()事件上,此代码启动一个重复计时器(在此示例中每 500 毫秒),一旦发生mouseup()事件就会取消该计时器。 This should be adaptable to what you want:这应该适合你想要的:

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

function do_something() {
  // whatever
}

SeesetInterval() for more information on clearing timers.有关清除计时器的更多信息,请参阅setInterval()

I would use the javascript function setInterval() within a function that gets called on mouse down.我会在鼠标按下时调用的函数中使用 javascript 函数setInterval()

<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>
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
}

I see a problem with both solutions listed above.我发现上面列出的两种解决方案都有问题。

onmouseup is only triggered if the mouse is released while it is over the button. onmouseup仅在鼠标在按钮上方时被释放时才会触发。 If the user keeps the mouse down then moves the mouse away before releasing it then clearInterval is never fired and so do_something will fire forever.如果用户按住鼠标,然后在释放鼠标之前将鼠标移开,则永远不会触发clearInterval ,因此do_something将永远触发。

You would need to add another event, " onmouseout ", that also calls clearInterval .您需要添加另一个事件“ onmouseout ”,它也调用clearInterval

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM