内容介绍
最近事情有点多,参加新星计划也接近尾声,顾不上更新文章是个问题,最后决定水一篇,但是又不能太水,所以就有了学习时候的这个案例(论如何光明正大的水)。
一、效果图
二、实现代码
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>一个按钮控制定时器的开始与暂停</title>
<script type="text/javascript">
var intervalId;
var i = 0;
var count = 0;
function startTime() {
var hour = document.getElementById("hour");
var minute = document.getElementById("minute");
var second = document.getElementById("second");
var ms = document.getElementById("ms");
var buttonEle = document.getElementById("start");
if (i % 2 == 0) {
buttonEle.innerHTML = "暂停计时";
intervalId = setInterval(function() {
count += 1;
var thehour = parseInt(count / 360000);
var theminute = parseInt(count / 6000 % 60);
var thesecond = parseInt(count / 100 % 60);
var thems = parseInt(count % 100);
if (thehour >= 10) {
hour.innerHTML = thehour + " ";
} else {
hour.innerHTML = "0" + thehour + " ";
}
if (theminute >= 10) {
minute.innerHTML = theminute + " ";
} else {
minute.innerHTML = "0" + theminute + " ";
}
if (thesecond >= 10) {
second.innerHTML = thesecond + " ";
} else {
second.innerHTML = "0" + thesecond + " ";
}
if (thems >= 10) {
ms.innerHTML = thems + " ";
} else {
ms.innerHTML = "0" + thems + " ";
}
}, 10)
} else {
buttonEle.innerHTML = "开始计时";
clearInterval(intervalId);
}
i++;
}
</script>
<style type="text/css">
body,
html {
background: violet;
/*position: relative;*/
}
#firstDiv {
height: 50%;
width: 50%;
position: absolute;
margin-left: 350px;
margin-top: 150px;
background: #ffcccc;
}
#twoDiv {
height: 200px;
width: 100%;
position: absolute;
margin-top: 130px;
margin-left: 130px;
;
}
span {
font-size: 30px;
}
button {
font-size: 20px;
}
</style>
</head>
<body>
<div id="firstDiv">
<div id="twoDiv">
<span><span id="hour">00 </span>时</span>
<span><span id="minute">00 </span>分</span>
<span><span id="second">00 </span>秒</span>
<span><span id="ms">00 </span>毫秒</span>
<button id="start" onclick="startTime()">开始计时</button>
</div>
</div>
</body>
</html>
三、注
案例不分大小,有想法的小伙伴可以优化结构布局,重新封装函数,或者增加更多有趣的功能,如重置按钮、分段计时等。
标签:JavaScript,定时器
更多演示案例,查看 案例演示
欢迎评论留言!