目录
1、css代码
2.html代码
3.js代码
1、css代码
.box {
position: relative;
width: 600px;
height: 600px;
background: url(./images/clock.jpg) no-repeat center;
}
.hour,
.minute,
.second {
position: absolute;
left: 0;
top: 0;
width: 100%;
height: 100%;
}
.hour {
background: url(./images/hour.png) no-repeat center;
transform: rotate(270deg);
}
.minute {
background: url(./images/minute.png) no-repeat center;
transform: rotate(0deg);
}
.second {
background: url(./images/second.png) no-repeat center;
transform: rotate(0deg);
}
2.html代码
<div class="box">
<div class="hour">
</div>
<div class="minute">
</div>
<div class="second">
</div>
</div>
3.js代码
创建日期对象,获取当前时间,计算秒针,时针,分针转一圈的度数,来设置每秒的旋转度数
角度换算:
小时角度公式:小时 * 30 + 分钟 / 60 * 30
分钟角度公式:分钟* 6 + 秒 / 60 * 6
秒角度公式: 当前秒数 * 6
获取当前时分秒
多次调用定时器,重复获取时间,让指针动起来
const second = document.querySelector('.second')
const hour = document.querySelector('.hour')
const minute = document.querySelector('.minute')
function getTime() {
let date = new Date()
let h = date.getHours()
let m = date.getMinutes()
let s = date.getSeconds()
const h_rotate = h * 30 + (m / 60) * 30
const m_rotate = m * 6 + (s / 60) * 6
const s_rotate = s * 6
hour.style.transform = `rotate(${h_rotate})deg`
minute.style.transform = `rotate(${m_rotate}deg)`
second.style.transform = `rotate(${s_rotate}deg)`
}
getTime()
setInterval(getTime, 1000)