在 javascript 中长按按钮时计算秒数

Count seconds on button long press in javascript

本文关键字:计算 按钮 javascript      更新时间:2023-09-26

我想使用 javascript 计算按钮一次按下(长按)多少时间的秒数,是否有任何函数或事件在长按按钮时触发?

mousedown

按住鼠标按钮时触发,mouseup在松开鼠标按钮时触发。

通过使用变量,您可以确定何时按住按钮,何时不按住按钮。

您需要混合mousedownmouseup事件才能实现您想要的。

像这样:

var timer = 0,
    timerInterval,
    button = document.getElementById("button");
button.addEventListener("mousedown", function() {
  timerInterval = setInterval(function(){
    timer += 1;
    document.getElementById("timer").innerText = timer;
  }, 1000);
});
button.addEventListener("mouseup", function() {
  clearInterval(timerInterval);
  timer = 0;
});
<button id="button">Button</button>
<div id="timer">0</div>