最近几天在做一个小项目,需要用到一个计时器的效果,效果图如下:
当用户点击开始按钮开始计时,点击暂停按钮暂停计时,捣鼓了一下弄出了个效果,不过这个效果也是参考了网上的一些资料,废话不多说,先上代码:
timer.gif
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1.0,maximum-scale=1, user-scalable=no" />
<title>南方电网95598</title>
<style>
*{
margin: 0;
padding: 0;
}
.start-number{
margin: 50px auto;
width: 200px;
text-align: center;
}
.start-number>img{
display: inline-block;
width: 30px;
margin: 0 2px;
}
</style>
<script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<input type="button" id="startBtn" value="开始" onclick="startTime()"/>
<input type="button" id="endBtn" value="暂停" onclick="stopTime()"/>
<input type="button" id="resetBtn" value="重置" onclick="reset()"/>
<div class="start-number" id="clockNum"></div>
<script>
$(function () {
startN("00:00");
})
// 计时器
var n= 0, timer=null,oNumber,imgStr="",speed=60, clockM, clockS;
// 开始计时
function startTime() {
clearInterval(timer);
timer=setInterval(function () {
imgStr ="";
n++;
clockM = parseInt(n/60);
clockS = parseInt(n%60);
oNumber=toDub(clockM)+":"+toDub(clockS);
for(var i=0;i<oNumber.length;i++){
var current = oNumber[i];
if(oNumber[i]==":"){
current = '10';
}
var oSpan= "<img src='"+"images/"+current+".png"+"'/>";
imgStr = imgStr + oSpan;
}
$("#clockNum").html(imgStr);
},1000/speed);
}
//暂停并且清空计时器
function stopTime() {
clearInterval(timer);
return oNumber;
}
//补零
function toDub(n){
return n<10?"0"+n:""+n;
}
// 拆分数字为图片
function startN(num) {
var num = num;
var imgStr = '';
for(var i=0;i<num.length;i++){
var current = num[i];
if(num[i]==":"){
current = '10';
}
var oSpan= "<img src='"+"images/"+current+".png"+"'/>";
imgStr = imgStr + oSpan;
}
$("#clockNum").html(imgStr);
}
//重置计时器
function reset() {
clearInterval(timer);
n= 0;
oNumber=0;
clockM=0;
clockS=0;
startN("00:00");
}
</script>
</body>
</html>
各位如果有更好的方法可以留言共享指正
网友评论