Javascript - 通过键盘按键启动和停止

Javascript - start and stop with keypress from keyboard

我有这个 javascript http://jsfiddle.net/ZDsMa/433/ 来选择一个随机数。我把它放在 html div 上,我想用 keypress 而不是 onClick 开始打乱数字,也想用 keypress

再次停止
 var output, started, duration, desired;

// Constants
duration = 5000;
desired = '5';

// Initial setup
output = $('#output');
started = new Date().getTime();

// Animate!
animationTimer = setInterval(function() {
    // If the value is what we want, stop animating
    // or if the duration has been exceeded, stop animating
    if (output.text().trim() === desired || new Date().getTime() - started > duration) {
        clearInterval(animationTimer);
    } else {
        console.log('animating');
        // Generate a random string to use for the next animation step
        output.text(
            ''+
            Math.floor(Math.random() * 10)+
            Math.floor(Math.random() * 10)
        );
    }
}, 100);

您可以将动画包装在一个函数中,然后在按键时调用它...像这样:

var output, started, duration, desired;
var sel = [];
// Constants
duration = 5000;
desired = '5';

// Initial setup
output = $('#output');

var keyPressed = false;

$(document).keypress(function(){
 if (!keyPressed){
   started = new Date().getTime();
   scramble();
    keyPressed = true;
  }
  else{
   keyPressed = false;
  }
});

// Animate!
var scramble = function(){
 animationTimer = setInterval(function() {
    // If the value is what we want, stop animating
    // or if the duration has been exceeded, stop animating
    if (output.text().trim() === desired || new Date().getTime() - started > duration || !keyPressed) {
      while($.inArray(output.text().trim(),sel)>-1){
         output.text(
              ''+
              Math.floor(Math.random() * 10)+
              Math.floor(Math.random() * 10)
          );
        }
        clearInterval(animationTimer);
        keyPressed = false;
        sel.push(output.text());
        $("#selected").text(sel);
    } else {
        
        // Generate a random string to use for the next animation step
        output.text(
            ''+
            Math.floor(Math.random() * 10)+
            Math.floor(Math.random() * 10)
        );
        
    }
 }, 100);
}
#output {
    margin: 20px;
    padding: 20px;
    background: gray;
    border-radius: 10px;
    font-size: 80px;
    width: 80px;
    color: white;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="output">--</div>
<div id="selected"></div>