<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>计时器</title>
<style>
#clock {
width: 200px;
height: 50px;
margin-bottom: 20px;
color: #0ff;
font-size: 20px;
line-height: 50px;
text-align: center;
background-color: #333;
border-radius: 25px;
}
.stop {
color: #f00 !important;
}
</style>
</head>
<body>
<div id="clock"></div>
<button id="btn">停止</button>
<script>
//输出时间
function getDate(){
var dobj = new Date();
var year = dobj.getFullYear();
var month = dobj.getMonth()+1;
var date = dobj.getDate();
var minutes = dobj.getMinutes();
var seconds = dobj.getSeconds();
//转换成两位数函数
function toDouble(n){
if(n<10){
n = '0' + n;
}
return n;
}
var str = year + '-' + toDouble(month) + '-' + toDouble(date) + ' ' + toDouble(minutes) + ':' + toDouble(seconds);
var clock = document.getElementById('clock');
clock.innerHTML = str;
}
getDate(); //先设置时间
var setItv = setInterval(getDate,1000);
var btnObj = document.getElementById('btn');
var i =0;
btnObj.οnclick=function(){
i++;
if(i/2%1){
this.innerHTML='开始';
clock.classList.add('stop');
clearInterval(setItv);
}
else{
this.innerHTML='停止';
clock.classList.remove('stop');
getDate();
setItv = setInterval(getDate,1000); //这里要用全局变量
}
}
</script>
</body>
</html>
定时器
最新推荐文章于 2024-08-04 20:14:50 发布