第一个setInterval实现的是在span标签中实现时钟效果。
思路:首先给每个span定义id名,然后在下面写定时器setInterval。通过new Date()获得当前日期,在根据getHours、getMinutes、getSeconds获取时分秒。最后通过id.innerHTML来得到里面的元素。
第二个setInterval实现的是用图片的方式来实现时钟效果。
思路:原理同上,不过需要通过计算时分秒的个位和十位的数字来修改图片地址。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<span id="hS"></span>:
<span id="mS"></span>:
<span id="sS"></span>
<img id="hsImg" src="./img/img/0.png" alt="" /><img id="hgImg" src="./img/img/0.png" alt="" />:
<img id="fsImg" src="./img/img/0.png" alt="" /><img id="fgImg" src="./img/img/0.png" alt="" />:
<img id="ssImg" src="./img/img/0.png" alt="" /><img id="sgImg" src="./img/img/0.png" alt="" />
<script>
function box() {
var now = new Date();
var h = now.getHours();
var m = now.getMinutes();
var s = now.getSeconds();
if (h < 10) {
h = "0" + h;
}
if (m < 10) {
m = "0" + m;
}
if (s < 10) {
s = "0" + s;
}
hS.innerHTML = h;
mS.innerHTML = m;
sS.innerHTML = s;
}
box(); // 一开始调用一次
setInterval(box, 1000);//每隔 1000毫秒 执行一次 函数
setInterval(function() {
var now = new Date();
var miao = now.getSeconds();
var sg = miao % 10;
var ss = parseInt(miao / 10) % 10;
//根据秒钟的个位 十位 来修改 图片的地址
sgImg.src = "./img/img/" + sg + ".png";
ssImg.src = "./img/img/" + ss + ".png";
var fen = now.getMinutes();
var fg = fen % 10;
var fs = parseInt(fen / 10) % 10;
fgImg.src = "./img/img/" + fg + ".png";
fsImg.src = "./img/img/" + fs + ".png";
var hour = now.getHours();
var hg = hour % 10;
var hs = parseInt(hour / 10) % 10;
hgImg.src = "./img/img/" + hg + ".png";
hsImg.src = "./img/img/" + hs + ".png";
}, 1000);
</script>
</body>
</html>