一款简单漂亮的jQuery计时器插件。该计时器插件可以实现秒、分钟和小时的计时功能,并带有开始、暂停和重新开始计时的按钮功能。
该计时器插件的计时功能依赖于jquery-runner插件。
<link rel="stylesheet" type="text/css" href="style.css">
<script src="js/jquery.min.js"></script>
<script src="js/jquery-runner.js"></script>
DEMO中的计时器代码的HTML结构使用Bootstrap来进行布局,其结构如下:
<div class="container-fluid">
<div class="col-xs-12 fill">
<span id="runner"></span><br><br>
<div class="col-sm-10 col-sm-offset-2">
<div class="col-xs-4 col-sm-3 centered"><button id="stopBtn"></button></div>
<div class="col-xs-4 col-sm-3 centered"><button id="startBtn"></button></div>
<div class="col-xs-4 col-sm-3 centered"><button id="resetBtn"></button></div>
</div>
</div>
</div>
在页面DOM元素初始化完毕之后,可以通过下面的方法来初始化该计时器插件。
$('#runner').runner({
milliseconds: false,
format: function millisecondsToString(milliseconds) {
var oneHour = 3600000;
var oneMinute = 60000;
var oneSecond = 1000;
var seconds = 0;
var minutes = 0;
var hours = 0;
var result;
if (milliseconds >= oneHour) {
hours = Math.floor(milliseconds / oneHour);
}
milliseconds = hours > 0 ? (milliseconds - hours * oneHour) : milliseconds;
if (milliseconds >= oneMinute) {
minutes = Math.floor(milliseconds / oneMinute);
}
milliseconds = minutes > 0 ? (milliseconds - minutes * oneMinute) : milliseconds;
if (milliseconds >= oneSecond) {
seconds = Math.floor(milliseconds / oneSecond);
}
milliseconds = seconds > 0 ? (milliseconds - seconds * oneSecond) : milliseconds;
if (hours > 0) {
result = (hours > 9 ? hours : "0" + hours) + ":";
} else {
result = "00:";
}
if (minutes > 0) {
result += (minutes > 9 ? minutes : "0" + minutes) + ":";
} else {
result += "00:";
}
if (seconds > 0) {
result += (seconds > 9 ? seconds : "0" + seconds);
} else {
result += "00";
}
return result;
}
});
开始计时按钮、停止计时按钮和重置按钮分别要添加相应的方法,以及在点击的时候添加和移除相应的class类。
$('#startBtn').click(function() {
$('#runner').runner('start');
$(this).addClass('activeBtn');
$('#stopBtn').removeClass('activeBtn');
});
$('#stopBtn').click(function() {
$('#runner').runner('stop');
$(this).addClass('activeBtn');
$('#startBtn').removeClass('activeBtn');
});
$('#resetBtn').click(function() {
$('#runner').runner('reset');
$('#stopBtn').removeClass('activeBtn');
$('#startBtn').removeClass('activeBtn');
});