简体   繁体   English

Javascript 在鼠标状态为“保持”时调用 function

[英]Javascript calling a function while having a mousestate of 'hold'

I am creating a javascript canvas background and I want items on the screen to move only when I am holding down my mouse button (anywhere on the screen).我正在创建 javascript canvas 背景,并且我希望屏幕上的项目仅在按住鼠标按钮(屏幕上的任何位置)时移动。

window.addEventListener('mousedown',function(e) {
       console.log("mousedown");
})

This is the code I have now.这是我现在拥有的代码。 How can I a function be called while I am holding down the mouse button, and not just on-click?我如何在按住鼠标按钮而不是单击时调用 function?

Thanks a lot.非常感谢。

window.addEventListener('mousedown',function(e) {
       holding = 1;
})


window.addEventListener('mouseup',function(e) {
       holding = 0;
})

If you use this, you can later check for if the variable of 'holding' is a 1 or a 0 as a conditional for a loop and have your function be running while holding == 1如果你使用它,你可以稍后检查'holding'的变量是1还是0作为循环的条件,并让你的function在保持== 1时运行

I believe it is an option for your question:我相信这是您问题的一个选择:

window.addEventListener('mousedown', function (e) {
   console.log("mousedown");
   //function to start animation
   window.addEventListener('mouseup', function (e) {
      console.log("mouseup");
      //function to end animation
   })
})

In this way the mouseup listener would be created only when its animation is started.这样,mouseup 监听器只会在其 animation 启动时创建。

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

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