我有一个 HTML5“范围”控件,我想在其两侧添加加号 (+) 和减号 (-) 按钮。
fiddle 工作正常,只是在'click and hold' 时值增加(或减少)一次。 虽然我希望它应该持续增加(或减少)。
HTML,
<input type='button' id='minus'/>
<div class='range-container'>
<input id='range' type='range' min='0' max='100' step='1'/>
</div>
<input type='button' id='plus'/>
JavaScript,
$('#plus').click(function() {
$('#range').val(parseInt($('#range').val()) + 1);
});
$('#minus').click(function() {
$('#range').val(parseInt($('#range').val()) - 1);
});
HTML5 的“数字”控件本身就有这种体验。
通过SO查看,无法在任何地方找到这个问题。我最接近的是,this ,同样只需要一次点击。
最佳答案
您可以使用requestAnimationFrame
不断检查是否有任何按钮仍被按下。如果仍然按下,您可以增加或减少您的值。
- 创建一个从零开始的“数字”变量。
- 如果按下添加按钮,将“isDown”变量设置为 1。
- 如果按下减法按钮,则将“isDown”变量设置为 -1。
- 如果有任何按钮被释放,将'isDown'变量设置为0;
- 启动一个
requestAnimationFrame
循环,不断检查“isDown”是否不为零。如果不为零,则 requestAnimationFrame 通过 isDown 值更改“数字”变量。
这是示例代码和演示:
var $result=$('#result');
var number=0;
var isDown=0;
var delay=250;
var nextTime=0;
requestAnimationFrame(watcher);
$("button").mousedown(function(e){handleMouseDown(e);});
$("button").mouseup(function(e){handleMouseUp(e);});
$("button").mouseout(function(e){handleMouseUp(e);});
function handleMouseDown(e){
// tell the browser we're handling this event
e.preventDefault();
e.stopPropagation();
// Put your mousedown stuff here
isDown=(e.target.id=='Add')?1:-1;
}
function handleMouseUp(e){
// tell the browser we're handling this event
e.preventDefault();
e.stopPropagation();
// Put your mouseup stuff here
isDown=0;
}
function watcher(time){
requestAnimationFrame(watcher);
if(time<nextTime){return;}
nextTime=time+delay;
if(isDown!==0){
number+=isDown;
$result.text(number);
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<button id=Add>Add</button>
<button id=Subtract>Subtract</button>
<span id='result'>0</span>
关于javascript - 按住鼠标连续增加值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28127507/