当鼠标单击并按住元素加号时,我想增大或减小值,它正在工作,但在鼠标保持上不起作用
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()">