本文实例为大家分享了js实现电子时钟的具体代码,供大家参考,具体内容如下
index.html
<!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>数字时钟</title>
<link rel="stylesheet" href="index.css" >
</head>
<body>
<div class="wrap">
<div class="item">0</div><!-- 0~2 -->
<div class="item">0</div><!-- 0~9 -->
<div class="colon">:</div>
<div class="item">0</div><!-- 0~6 -->
<div class="item">0</div><!-- 0~9 -->
<div class="colon">:</div>
<div class="item">0</div><!-- 0~6 -->
<div class="item">0</div><!-- 0~9 -->
</div>
<script src="clock.js"></script>
</body>
</html>
index.css
* {
margin: 0;
padding: 0;
}
body {
background-color: black;
}
.wrap {
width: 800px;
height: 100px;
background-color: #355da7;
border-radius: 10px;
position: absolute;
left: 0;
top: 0;
right: 0;
bottom: 0;
margin: auto;
display: flex;
}
.wrap .item,
.wrap .colon {
flex: 1;
text-align: center;
line-height: 100px;
font-size: 70px;
font-weight: 100;
color: wheat;
}
clock.js
let item = document.getElementsByClassName("item");
function changeTime() {
setInterval(function() {
let hour = new Date().getHours();
let minute = new Date().getMinutes();
let sec = new Date().getSeconds();
let hourItem = handleTime(hour);
let minuteItem = handleTime(minute);
let secItem = handleTime(sec);
item[0].innerHTML = hourItem[0];
item[1].innerHTML = hourItem[1];
item[2].innerHTML = minuteItem[0];
item[3].innerHTML = minuteItem[1];
item[4].innerHTML = secItem[0];
item[5].innerHTML = secItem[1];
},1000)
}
changeTime();
function handleTime(number) {
let arr = [];
//23 =2--3
//11 =1--1
//10 % 10 = 1--0
//5 % 10 = 0--5
let a = number % 10;
let b = (number - a) / 10;
arr.push(b,a);
return arr;
}
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持编程网。