JS制作时钟实例:
主要使用:
定时器:
1.定义
sobj=setInterval(function(){
//每隔一秒钟执行此代码段
},1000)
2.清除
claerInterval(sobj);
-
CSS样式:
#clock {
height: 50px;
width: 500px;
border-radius: 50px;
background: #000;
color: blue;
font-weight: bold;
text-align: center;
line-height: 50px;
}
* {
font-size: 30px;
}
#button {
margin-left: 150px;
}
-
HTML部分:
<body>
<div id="clock">
<span id="sid">随意初值</span>
</div>
<div id="button">
<button id="abt">暂停</button>
<button id="bbt">开始</button>
</div>
</body>
-
JS部分:
<script type="text/javascript"> function getDate() { dobj = new Date(); year = dobj.getFullYear(); month = dobj.getMonth() + 1; //不能在下面用 month = '0' + month+1代替此处+1; if (month < 10) { month = '0' + month; //此处‘+’为字符串连接,不做数学运算 } date = dobj.getDate(); if (date < 10) { date = '0' + date; } hour = dobj.getHours(); if (hour < 10) { hour = '0' + hour; } minute = dobj.getMinutes(); if (minute < 10) { minute = '0' + minute; } second = dobj.getSeconds(); if (second < 10) { second = '0' + second; } str = year + '/' + month + '/' + date + ' ' + hour + ':' + minute + ':' + second; sidobj = document.getElementById('sid'); sidobj.innerHTML = str; } getDate(); //获得初始时间 start(); //调用start函数 //定时器开始启用秒表 function start() { sobj = setInterval(function() { getDate(); //每隔一段时间执行一次 }, 1000); } //也可用setInterval(getDate,1000);代替函数体中的值 //暂停 function close() { clearInterval(sobj); } abtobj = document.getElementById('abt'); abtobj.onclick = function() { close(); } //开始 bbtobj = document.getElementById('bbt'); bbtobj.onclick = function() { start(); } </script>