当鼠标在元素上单击并按住时,我想增加或减少值,它可以工作但不能在鼠标按住时工作
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
如下所示以及 onMouseDown
和 onMouseUp
事件
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/