按住鼠标的 Javascript 增加值更快

use*_*585 6 javascript jquery

我有这个脚本,每次单击按钮时都会将值加 1:

<script>
    function incrementValue(id) {
       var value = parseInt(document.getElementById(id).innerHTML);
       value = value + 1;
       document.getElementById(id).innerHTML = value;
    }
</script>

<button onclick="incrementValue('skill_1')"> add </button><br>
<span id=skill_1>0</span>
Run Code Online (Sandbox Code Playgroud)

但是我想调整它,这样如果我按住鼠标按钮,它就会重复,所以我不必一遍又一遍地按下它。

有什么办法可以使用 javascript 做到这一点?或者jquery适合吗?

Ror*_*san 7

为此,您需要使用该mousedown事件来启动超时(这是增量计数开始之前的延迟)和间隔(进行重复计数)。您还需要一个mouseupandmouseleave处理程序来删除这两个计时器。尝试这个:

var timeout, interval;

[].forEach.call(document.querySelectorAll('.add'), function(button) {
  button.addEventListener('mousedown', function() {
    var id = button.dataset.target;
    incrementValue(id);
    
    timeout = setTimeout(function() {
      interval = setInterval(function() {
        incrementValue(id);
      }, 50);    
    }, 300);
  });
  
  button.addEventListener('mouseup', clearTimers);
  button.addEventListener('mouseleave', clearTimers); 
  
  function clearTimers() {
    clearTimeout(timeout);
    clearInterval(interval);
  }
});

function incrementValue(id) {
  var el = document.getElementById(id);
  var value = parseInt(el.textContent, 10);
  document.getElementById(id).textContent = ++value;
}
Run Code Online (Sandbox Code Playgroud)
<button class="add" data-target="skill_1">add</button><br />
<span id="skill_1">0</span>
Run Code Online (Sandbox Code Playgroud)


Ori*_*ori 5

您将需要 3 个事件处理程序:

  1. mousedown这将调用一个函数,该函数将continuosIncerment在按下鼠标按钮时以超时 ( )调用自身。
  2. mouseup 这将在释放按钮时清除超时。
  3. mouseleave 当鼠标离开按钮区域时清除超时。

const btn = document.querySelector('#btn');
const skill_1 = document.querySelector('#skill_1');
let value = 0;
let timer;

function continuosIncerment() {
  skill_1.innerHTML = ++value;
  
  timer = setTimeout(continuosIncerment, 200);
}

function timeoutClear() {
  clearTimeout(timer);
}

btn.addEventListener('mousedown', continuosIncerment);

btn.addEventListener('mouseup', timeoutClear);

btn.addEventListener('mouseleave', timeoutClear);
Run Code Online (Sandbox Code Playgroud)
<button id="btn"> add </button><br>
<span id="skill_1">0</span>
Run Code Online (Sandbox Code Playgroud)