JavaScript_Digital Clock

Effect picture:

Insert picture description here

demand analysis:

  1. Get time by date
  2. Get the time dynamically through the interval timer setInterval
  3. The interval timer setInterval is set to 1000 milliseconds (1 second) to obtain the time
  4. 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:

Insert picture description here

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.

Guess you like

Origin blog.csdn.net/qq_45677671/article/details/113663019