在鼠标保持时连续递增值

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看,在任何地方找不到这个问题.我得到的最近的是,只是一次点击.

mar*_*rkE 6

您可以使用requestAnimationFrame不断检查是否仍按下任何按钮.如果仍然按下,您可以增加或减少您的值.

  • 创建一个从零开始的'number'变量.
  • 如果按下"添加"按钮,请将"isDown"变量设置为1.
  • 如果按下Subtract按钮,请将'isDown'变量设置为-1.
  • 如果释放任何按钮,则将'isDown'变量设置为0;
  • 启动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)

  • 很好地使用`requestAnimationFrame()`,但我一直在尝试使用`setInterval()`. (2认同)
  • @Tomalak,它在现代浏览器中得到了相当好的支持.如果您使用的是较旧的浏览器,请检查此链接,该链接包含一个polyfill,如果requestAnimationFrame不可用,则返回使用setInterval:http://creativejs.com/resources/requestanimationframe/ (2认同)