js计时器
版权声明:本文为博主原创文章,未经博主允许不得转载。
思路:
1、将每个时间的id都获取到,因为有零所以一个时间要有两个id。
2、先让后面的递增,之后判断递增多少后,前面的+1。
3、用innerHTML改变他的HTML元素(也就是把时间输出在HTML中)。
展示图
HTML+CSS代码:
<html lang="zh-CN"> <head> <meta charset="UTF-8"> <title>js计时</title> <style> body { text-align: center; background: url(https://api.xfyun.club/cos.php) no-repeat; background-size: cover; color: white; } .xf { width: 80%; height: 500px; border: 3px solid black; border-radius: 30px; background-color: rgba(71, 71, 71, 0.383); margin: 100px auto; font-size: 30px; font-family: '微软雅黑', 'Franklin Gothic Medium', 'Arial Narrow', Arial, sans-serif; } .xf-2 { margin-top: 10%; } #data { font-weight: 100; font-size: 19px; } .de { font-family: "楷体"; margin-top: 5%; font-size: 24px; font-weight: bold; } </style> </head> <body id="body"> <div class="xf"> <div class="xf-2"> 从你进来已经过了<span id="d">0</span><span id="dd">0</span> 天 <span id="h">0</span><span id="hh">0</span> 时 <span id="m">0</span><span id="mm">0</span> 分 <span id="s">0</span><span id="ss">0</span> 秒 <div class="de">现在时间为: <span id="data"></span></div> </div> </div> <script type="text/javascript"> var d = document.getElementById('d'), dd = document.getElementById('dd'), h = document.getElementById('h'), hh = document.getElementById('hh'), m = document.getElementById('m'), mm = document.getElementById('mm'), s = document.getElementById('s'), ss = document.getElementById('ss'), data = document.getElementById('data'), wz = document.getElementById('wz'); data.innerHTML = new Date(); setInterval(function () { ss.innerHTML++; if (ss.innerHTML >= 10) { s.innerHTML++; ss.innerHTML = 0; } if (s.innerHTML >= 6) { mm.innerHTML++; s.innerHTML = 0; } if (mm.innerHTML >= 10) { m.innerHTML++; mm.innerHTML = 0; } if (m.innerHTML >= 6) { hh.innerHTML++; m.innerHTML = 0; } if (hh.innerHTML >= 9) { h.innerHTML++; hh.innerHTML = 0; } if (h.innerHTML >= 2 && hh.innerHTML >= 4) { dd.innerHTML++ h.innerHTML = 0; hh.innerHTML = 0; } if (dd.innerHTML >= 9) { d.innerHTML++; dd.innerHTML = 0 } }, 1000); </script> </body> </html>
js代码:
var d = document.getElementById('d'), dd = document.getElementById('dd'), h = document.getElementById('h'), hh = document.getElementById('hh'), m = document.getElementById('m'), mm = document.getElementById('mm'), s = document.getElementById('s'), ss = document.getElementById('ss'), data = document.getElementById('data'), wz = document.getElementById('wz'); data.innerHTML = new Date(); setInterval(function () { ss.innerHTML++; if (ss.innerHTML >= 10) { s.innerHTML++; ss.innerHTML = 0; } if (s.innerHTML >= 6) { mm.innerHTML++; s.innerHTML = 0; } if (mm.innerHTML >= 10) { m.innerHTML++; mm.innerHTML = 0; } if (m.innerHTML >= 6) { hh.innerHTML++; m.innerHTML = 0; } if (hh.innerHTML >= 9) { h.innerHTML++; hh.innerHTML = 0; } if (h.innerHTML >= 2 && hh.innerHTML >= 4) { dd.innerHTML++ h.innerHTML = 0; hh.innerHTML = 0; } if (dd.innerHTML >= 9) { d.innerHTML++; dd.innerHTML = 0 } }, 1000);