数字时钟
代码
<!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> <img src="img/0.JPG" alt=""> <img src="img/0.JPG" alt=""> <img src="img/colon.JPG" alt=""> <img src="img/0.JPG" alt=""> <img src="img/0.JPG" alt=""> <img src="img/colon.JPG" alt=""> <img src="img/0.JPG" alt=""> <img src="img/0.JPG" alt=""> </div> <script> var imgs = document.getElementsByTagName('img'); setInterval(auto, 1000); function auto() { // 每次定时器发生 重新获取时间 var date = new Date(); var hours = date.getHours(); var minutes = date.getMinutes(); var seconds = date.getSeconds(); var currentTime = addZero(hours) + ':' + addZero(minutes) + ':' + addZero(seconds); // console.log(currentTime); // 09:48:07 for (var i = 0; i < imgs.length; i++) { if (isNaN(currentTime[i])) { // 是不是不是数字 true-对,不是数字 imgs[i].src = 'img/colon.JPG'; } else { // false 是数字 imgs[i].src = 'img/' + currentTime[i] + '.JPG' } } } auto(); // 加0函数 function addZero(time) { return time >= 10 ? time : '0' + time; } </script> </body> </html>