我在为我们学校的篮球队做一个时钟。一个射击时钟是一个计时器,从24秒开始倒数。我现在有定时器的骨架,但是我需要有特定的键绑定。键绑定应该允许我休息、暂停和播放计时器。
var count=24;
var counter=setInterval(timer, 1000);
function timer()
{
count=count-1;
if (count <= 0)
{
clearInterval(counter);
return;
}
document.getElementById("timer").innerHTML=count + " secs";
}发布于 2016-02-11 03:22:32
我还不能发表评论,但我建议查看这篇文章Binding arrow keys in JS/jQuery
链接文章解释了如何使用js/jquery绑定箭头键。使用http://keycode.info/,您可以找到所需密钥的密钥代码,并替换当前值,然后继续从那里构建代码。
发布于 2016-02-11 05:02:00
下面是我的代码示例:http://codepen.io/anon/pen/vLvWJM
$(document).ready(function() {
var $timer = $('#timer');
var $timerStatus = $('#timerStatus');
var timerValue = 24;
var intervalId = null;
var timerStatus = 'stopped';
if(!$timer.length) {
throw 'This timer is missing a <div> element.';
}
$(document).keydown(function(k) {
if(k.which == 80) {
if(timerStatus === 'playing') {
clearInterval(intervalId);
timerStatus = 'stopped';
updateTimerStatus();
return;
}
intervalId = setInterval(function() {
playTimer();
timerStatus = 'playing';
updateTimerStatus();
}, 1000);
} else if(k.which == 82) {
clearInterval(intervalId);
resetTimer();
updateText();
timerStatus = 'stopped';
updateTimerStatus();
}
});
function playTimer() {
if(timerValue > 0) {
timerValue--;
updateText();
}
}
function resetTimer() {
timerValue = 24;
}
function updateText() {
$timer.html(timerValue);
}
function updateTimerStatus() {
$timerStatus.html(timerStatus);
}
});<div id="timerStatus">stopped</div>
<div id="timer">24</div>
https://stackoverflow.com/questions/35330142
复制相似问题