javascript - 如何在 JavaScript 中连续增加或减少值

标签 javascript html

当鼠标在元素上单击并按住时,我想增加或减少值,它可以工作但不能在鼠标按住时工作

var salainv = document.getElementById("sala").value;
var bodegainv = document.getElementById("bodega").value;

function incrementar() {
  document.getElementById("sala").value = salainv++;
  document.getElementById("bodega").value = bodegainv--;
}

function decrementar() {
  document.getElementById("sala").value = salainv--;
  document.getElementById("bodega").value = bodegainv++;
}
<input type="number" name="bodega" id="bodega" value="15">
<input type="number" name="sala" id="sala" value="5">
<img src="https://cdn.pixabay.com/photo/2012/04/13/00/21/plus-31216_960_720.png" style="width: 40px;" onClick="incrementar()">
<img src="http://images.clipartpanda.com/minus-clipart-RTA7dagTL.png" style="width: 40px;" onClick="decrementar()">

谁能帮我让它在按下鼠标时工作?

谢谢。

最佳答案

您可以使用 setInterval如下所示以及 onMouseDownonMouseUp 事件

var salainv = document.getElementById("sala").value;
var bodegainv   = document.getElementById("bodega").value;

var timerId;
function incrementar() {
      document.getElementById("sala").value = salainv++;    
      document.getElementById("bodega").value = bodegainv--; 
 }
 function beginIncrementar(){
     timerId = setInterval(incrementar,200);
 }
 function endIncrementar(){
     clearInterval(timerId)
 }
 function decrementar() {
      document.getElementById("sala").value = salainv--;
      document.getElementById("bodega").value = bodegainv++; 
 }
 
 function beginDecrementar(){
     timerId = setInterval(decrementar,200);
 }
 function endDecrementar(){
     clearInterval(timerId)
 }
<input type="number" name="bodega" id="bodega" value="15">
<input type="number" name="sala" id="sala" value="5">
<img src="https://cdn.pixabay.com/photo/2012/04/13/00/21/plus-31216_960_720.png" style="width: 40px;" onClick="incrementar()" onMouseDown="beginIncrementar()" onMouseUp="endIncrementar()">
<img src="http://images.clipartpanda.com/minus-clipart-RTA7dagTL.png" style="width: 40px;" onClick="decrementar()" onMouseDown="beginDecrementar()" onMouseUp="endDecrementar()">

关于javascript - 如何在 JavaScript 中连续增加或减少值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43393973/

相关文章:

javascript - 模块化 JS 中的类扩展

javascript - HTML 标签显示在 ckeditor 底部

javascript - dgrid - 可编辑字段之间的键选项卡导航

javascript - 如何使用 spotify web api 获取用户的播放列表列表?

javascript - 如何更改脚本生成的 HTML 中的属性?

javascript - javascript 中的访问修饰符

html - 幻灯片菜单最后 2 个元素符号不起作用

javascript - 如何在CasperJS中编写基于数组的文件

html - 显示 flex 的回退

JavaScript 求和表值