Article Directory
Effect picture:
demand analysis:
- Get time by date
- Get the time dynamically through the interval timer setInterval
- The interval timer setInterval is set to 1000 milliseconds (1 second) to obtain the time
- In order to look good, we use digital pictures instead of numbers
Source code:
- HTML part
<div id="div">
<img src="img/0.png" />
<img src="img/0.png" />
时
<img src="img/0.png" />
<img src="img/0.png" />
分
<img src="img/0.png" />
<img src="img/0.png" />
秒
</div>
- css part
<style>
/*无*/
</style>
- JavaScript part
<script>
// 需求:数码时钟
var date = new Date();
var imgArr = document.getElementsByTagName('img');//获取img图片的一个集合
var hours,minutes,seconds;
var timre = setInterval(function () {
date = new Date();
// 获取小时
hours = date.getHours();
imgArr[0].src = "img/" + parseInt(hours / 10) + ".png"
imgArr[1].src = "img/" + hours % 10 + ".png"
// 获取分钟
minutes = date.getMinutes();
imgArr[2].src = "img/" + parseInt(minutes / 10) + ".png"
imgArr[3].src = "img/" + minutes % 10 + ".png"
// 获取秒
seconds = date.getSeconds();
imgArr[4].src = "img/" + parseInt(seconds / 10) + ".png"
imgArr[5].src = "img/" + seconds % 10 + ".png"
console.log(hours);
console.log(minutes);
console.log(seconds);
}, 1000)
</script>
- Total code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div id="div">
<img src="img/0.png" />
<img src="img/0.png" />
时
<img src="img/0.png" />
<img src="img/0.png" />
分
<img src="img/0.png" />
<img src="img/0.png" />
秒
</div>
</body>
</html>
<script>
// 需求:数码时钟
var date = new Date();
var imgArr = document.getElementsByTagName('img');//获取img图片的一个集合
var hours,minutes,seconds;
var timre = setInterval(function () {
date = new Date();
// 获取小时
hours = date.getHours();
imgArr[0].src = "img/" + parseInt(hours / 10) + ".png"
imgArr[1].src = "img/" + hours % 10 + ".png"
// 获取分钟
minutes = date.getMinutes();
imgArr[2].src = "img/" + parseInt(minutes / 10) + ".png"
imgArr[3].src = "img/" + minutes % 10 + ".png"
// 获取秒
seconds = date.getSeconds();
imgArr[4].src = "img/" + parseInt(seconds / 10) + ".png"
imgArr[5].src = "img/" + seconds % 10 + ".png"
}, 1000)
</script>
Picture used:
Since you don’t have pictures, you can copy the code directly and it won’t show the effect. You can find a few pictures to replace it and modify it slightly. As long as you can understand the code, the modification will not be a problem.