原生js实现动态时钟
程序员文章站
2022-05-30 09:25:32
...
原生js实现动态时钟
一、案例
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>时钟</title>
<style type="text/css">
* {
margin: 0;
padding: 0;
}
ul {
list-style-type: none;
}
.box {
position: relative;
width: 200px;
height: 200px;
border-radius: 50%;
margin: 20px auto;
background-color: #bdc2bb;
border-color: #fff;
}
.point {
position: absolute;
width: 6px;
height: 6px;
top: 98px;
left: 98px;
border-radius: 3px;
background-color: black;
}
.hour {
position: absolute;
width: 4px;
height: 50px;
background-color: blue;
left: 98px;
top: 50px;
transform-origin:center bottom;
}
.min {
position: absolute;
width: 3px;
height: 65px;
top: 35px;
left: 98.5px;
background-color: #278421;
transform-origin:center bottom;
}
.second {
position: absolute;
width: 2px;
height: 75px;
top: 25px;
left: 99px;
background-color: #266b86;
transform-origin:center bottom;
}
.list {
width: 200px;
height: 200px;
border-radius: 50%;
}
.list li {
position: absolute;
height: 192px;
width: 2px;
border-bottom: 4px solid #000;
top: 2px;
left: 99px;
transform: rotateZ(0);
}
.list li.lang {
height: 187px;
border-bottom: 10px solid #000;
transform: rotateZ(0);
}
</style>
</head>
<body>
<div class="box">
<div class="point"></div>
<div class="hour"></div>
<div class="min"></div>
<div class="second"></div>
<ul class="list"></ul>
</div>
<script type="text/javascript">
window.addEventListener("DOMContentLoaded", function(ev) {
var boxDom = getEles('box')[0];
var pointDom = getEles('point')[0];
var hourDom = getEles('hour')[0];
var minDom = getEles('min')[0];
var secondDom = getEles('second')[0];
var ulDom = getEles('list')[0];
var liDoms = [];
/*添加整点刻度*/
for (var i = 0; i < 60; i++) {
liDoms.push(createNode('li'));
}
liDoms[0].className = 'lang';
ulDom.appendChild(liDoms[0]);
/*在整点刻度内添加小刻度*/
liDoms.forEach(function(e, i) {
if (i % 5 == 0) {
liDoms[i].className = 'lang';
ulDom.appendChild(liDoms[i]);
} else {
ulDom.appendChild(liDoms[i]);
}
liDoms[i].style.transform = "rotateZ(" + i * 6 + "deg)";
});
/*初始时间指针位置*/
run();
/*每一秒调用一次重新设置时分秒针位置*/
var interval = setInterval(run,1000);
function run(){
var newDate = new Date();
var s = newDate.getSeconds();
secondDom.style.transform = "rotateZ("+s*6+"deg)";
var m = newDate.getMinutes()+s/60;
minDom.style.transform = "rotateZ("+m*6+"deg)";
var h = newDate.getHours()+m/60;
hourDom.style.transform = "rotateZ("+h*30+"deg)";
}
}, false);
function getEles(className) {
return document.getElementsByClassName(className);
}
function createNode(tagName) {
if (typeof tagName == "string") {
return document.createElement(tagName);
} else {
return console('输入不正确,请重新输入');
}
}
</script>
</body>
</html>
二、实现效果图