JavaScript之BOM 时钟效果
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>时钟效果</title>
<style>
.clock{
width: 600px;
height: 600px;
margin: 50px auto;
background: url(clock.jpg);
position: relative;
}
.clock div{
width: 20px;
height: 300px;
position: absolute;
top: 150px;
left:290px;
}
.hour{background: url(hour.png)no-repeat center center;}
.minute{background: url(minute.png)no-repeat center center;}
.second{background: url(second.png)no-repeat center center;}
</style>
</head>
<body>
<div class="clock">
<div class="hour"></div>
<div class="minute"></div>
<div class="second"></div>
</div>
<script>
let hour = document.getElementsByClassName("hour")[0];//获取页面时针元素
let minute = document.getElementsByClassName("minute")[0];//获取页面分针元素
let second = document.getElementsByClassName("second")[0];//获取秒针元素
let h = 0,m = 0,s = 0,ms = 0;//初始化时,分,秒一级毫秒的值为0
setInterval(function(){
let date = new Date();//获取最新时间
ms = date.getMilliseconds();//首先得到现在的毫秒数
s = date.getSeconds()+ ms / 1000;//然后得到秒 1.3s
m = date.getMinutes()+ s / 60;//再得到的是分钟数 45.6分钟
h = date.getHours() % 12 + m / 60;
//旋转角度
//一圈 360° 一共 60 秒 每秒6° 现在是 s秒
second.style.transform = "rotate(" + s * 6 + "deg)";
//变化 旋转 deg 度
minute.style.transform = "rotate(" + m * 6 + "deg)";
hour.style.transform = "rotate(" + h * 30 + "deg)";
},1000);
</script>
</body>
</html>