使用JavaScript按住鼠标时如何重复功能?

时间:2018-03-28 05:07:53

标签: javascript

尝试使用此代码按住鼠标左键重复运行某个功能,但它无法正常工作。任何想要纠正它的想法都将受到赞赏。

    var timer = 0;

    document.getElementById('myButton').onmousedown = function() {
        while (this.event) {
            timer = setInterval(function() {c_3()}, 100);
        }
        clearInterval(timer);
    }

2 个答案:

答案 0 :(得分:1)

你可以用多种方式解决这个问题

检查此https://codepen.io/hamidrezanikoonia/pen/bvarGL?editors=0011

 var interval_;

 document.getElementById('ele').onmousedown = function() {
 interval_ = setInterval(function(){ console.log("Hello"); }, 300);;
 }

  document.getElementById('ele').onmouseup = function() {
   clearInterval(interval_); wdsd
  }

我使用setInterval来执行此操作

答案 1 :(得分:0)

在按钮按下按钮时尝试添加mouseovermouseup个侦听器:

const button = document.querySelector('div');
button.addEventListener('mousedown', () => {
  let mouseIsDown = true;
  document.body.addEventListener('mouseup', () => clearTimeout(intervalLog));
  document.body.addEventListener('mouseover', (e) => {
    if (e.target !== button) clearTimeout(intervalLog);
  });
  const intervalLog = setInterval(() => console.log('mouse is down over button.'), 300);
});
<div>
button
</div>
<div>
div
</div>