ano*_*ias 9 javascript jquery html5
我有一个HTML5'范围'控件,我想在其中添加一个加号(+)和减号( - )按钮.
小提琴工作得很好,只是在"点击并按住"时值只增加(或减少)一次.我想要的是它应该不断增加(或减少).
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'/>
Run Code Online (Sandbox Code Playgroud)
JavaScript中,
$('#plus').click(function() {
$('#range').val(parseInt($('#range').val()) + 1);
});
$('#minus').click(function() {
$('#range').val(parseInt($('#range').val()) - 1);
});
Run Code Online (Sandbox Code Playgroud)
HTML5'数字'控件本身就有这种体验.
通过SO看,在任何地方找不到这个问题.我得到的最近的是,这只是一次点击.
您可以使用requestAnimationFrame不断检查是否仍按下任何按钮.如果仍然按下,您可以增加或减少您的值.
requestAnimationFrame循环,不断检查'isDown'是否为零.如果不为零,requestAnimationFrame会将'number'变量更改为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);
}
}Run Code Online (Sandbox Code Playgroud)
<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>Run Code Online (Sandbox Code Playgroud)