Javascript - 使用键盘按键启动和停止

时间:2015-12-16 16:14:25

标签: javascript jquery html javascript-events

我有这个javascript http://jsfiddle.net/ZDsMa/433/来挑选一个随机数。我把它放在html div上,我想开始用按键而不是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);

1 个答案:

答案 0 :(得分:1)

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

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>