时钟
实现目标
实现逻辑
- 通过Date类来获取当前时间
- 通过修改CSS样式的transform:rotate()来模拟时针分针秒针的走动
- 通过设置定时器来时刻修改样式
实现代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>2. JavaScript Clock</title>
</head>
<body>
<div class="clock">
<div class="clock-face">
<div class="hand hour-hand"></div>
<div class="hand min-hand"></div>
<div class="hand second-hand"></div>
</div>
</div>
<style>
html {
background: #018DED;
background-size: cover;
font-family: 'helvetica neue';
text-align: center;
font-size: 10px;
}
body {
margin: 0;
font-size: 2rem;
display: flex;
flex: 1;
min-height: 100vh;
align-items: center;
}
.clock {
width: 30rem;
height: 30rem;
border: 20px solid white;
border-radius: 50%;
margin: 50px auto;
position: relative;
padding: 2rem;
box-shadow: 0 0 0 4px rgba(0, 0, 0, 0.1),
inset 0 0 0 3px #EFEFEF,
inset 0 0 10px black,
0 0 10px rgba(0, 0, 0, 0.2);
}
.clock-face {
position: relative;
width: 100%;
height: 100%;
transform: translateY(-3px);
}
.hand {
width: 50%;
height: 6px;
position: absolute;
top: 50%;
transition: all .05s;
transform-origin:100%;
transition-timing-function: cubic-bezier(0.42,0,0.34,1.82);
transform:rotate(90deg);
}
.second-hand {
background: white;
}
.min-hand {
background: yellow;
}
.hour-hand {
background: lightcoral;
}
</style>
<script>
const secondHand = document.querySelector('.second-hand');
const minHand = document.querySelector('.min-hand');
const hourHand = document.querySelector('.hour-hand');
setclock();
function setclock(){
const currentTime = new Date();
const seconds = currentTime.getSeconds();
const min = currentTime.getMinutes();
const hour = currentTime.getHours();
const currentTimeseconds_deg = (seconds * 6 + 90) % 360;
const currentTimemin_deg = (min * 6 + ((seconds / 60) * 6) + 90) % 360;
const currentTimehour_deg = (hour * 30 + ((min/60) * 30) + ((seconds / 3600) * 30) + 90) % 360;
secondHand.style.transform = `rotate(${currentTimeseconds_deg}deg)`;
minHand.style.transform = `rotate(${currentTimemin_deg}deg)`;
hourHand.style.transform = `rotate(${currentTimehour_deg}deg)`;
}
setInterval(setclock,1000);
</script>
</body>
</html>
实现效果
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/c2dee64e4abf18392b684d45ae5e0098.gif#pic_center)
总结
- 使用了transition transform transition-timing-function transform-origin 来完成转动
- 在进入页面的时候调用了时钟函数,解决了进入页面时初始化的问题
- 把角度和360°取模,可以避免下面动图出现的一分钟整出现的跳帧现象,本质是角度400多度倒转回0度的动画
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/4ad77bc4562c141fda2b0b93f1acbc0a.gif#pic_center)