我有一个用javascript编写的计时器。当我在HTML页面中单击计时器时,它将暂停。如果我再次点击它,它将继续计数。
这是计时器代码:
var Timer = function() {}
Timer.prototype = {
refresh: null,
focus: null,
sec: 0,
min: 0,
hour: 0,
paused: false,
init: function(el) {
var that = this;
this.el = el;
this.clickEvent();
return this;
},
set: function(t) {
t = t.split(':');
this.hour = t[0];
this.min = t[1];
this.sec = t[2];
return this;
},
bindFocus: function() {
var that = this;
clearInterval(this.focus);
if (document.hasFocus)
that.focus = setInterval(function() {
if (document.hasFocus()) {
if (that.paused) {
window.clearInterval(this.refresh);
that.go();
}
} else
that.stop();
}, 200);
},
clickEvent: function() {
var that = this, frag = $('<h2>').addClass('pauseGame').text(texts.pause), toggleFlag = true;
this.el.bind('click', timerClicked);
function timerClicked(callback) {
if (!toggleFlag)
return;
toggleFlag = false;
if (that.paused === false) {
that.stop();
window.clearInterval(that.focus);
$('#options > button').not('#options > .pause').prop('disabled', true);
$('#options > .pause').text('Resume');
board.mainBoard.fadeOut(400, function() {
frag.css({
letterSpacing: '25px',
opacity: 0
});
$(this).after(frag).detach();
frag.parent().addClass('paused');
frag.animate({
opacity: 1
}, {
queue: false,
duration: 400
}).animate({
letterSpacing: '-4px'
}, 700, "easeOutBack", function() {
toggleFlag = true;
});
});
that.el.addClass('pause');
} else {
$('#options > button').prop('disabled', false);
$('#options > .pause').text('Pause');
options.undoToggle();
frag.animate({
opacity: 0,
letterSpacing: '25px'
}, 600, "easeInBack", function() {
$(this).parent().removeClass('paused').end().remove();
board.container.prepend(board.mainBoard).removeAttr('style');
board.mainBoard.fadeIn(400);
that.go();
toggleFlag = true;
});
this.className = '';
}
}
},
restart: function(el) {
this.sec = this.min = this.hour = 0;
this.el.text('00:00');
this.stop().go();
},
go: function(now) {
var that = this;
this.paused = false;
if (now)
updateClock();
window.clearInterval(this.refresh);
that.refresh = window.setInterval(updateClock, 1000);
function updateClock() {
that.sec++;
if (that.sec == 60) {
that.sec = 0;
that.min++;
}
if (that.sec < 10)
that.sec = "0" + that.sec;
if (that.min == 60) {
that.min = 0;
that.hour++;
}
var hours = (that.hour > 0) ? ((that.hour <= 9) ? "0" + that.hour : that.hour) + ":": '';
that.el.html(hours + ((that.min <= 9) ? "0" + that.min : that.min) + ":" + that.sec);
}
return this;
},
stop: function() {
this.paused = true;
window.clearInterval(this.refresh);
return this;
}
};
我还希望在单击按钮时暂停计时器,并在再次单击此按钮时恢复计时器(或计时器)。我当前的按钮代码是简单的HTML:
<div id="options">
<button class="pause" title="pause/resume the game">Pause</button>
</div>
那怎么这样呢?我想要它,如果你点击按钮或计时器没关系,两者都应暂停计时器或恢复计时器。
非常感谢
答案 0 :(得分:1)
您想模拟点击吗? This post will help you
答案 1 :(得分:0)
知道了:
timer.el.trigger('click');
为我做了诀窍