02 JS + CSS Clock
实现效果
钟表显示当前时间。
实现效果预览
git上有更详细的分析
分析
指针旋转效果:
利用JS设置transform:rotate(90deg)
来实现旋转效果
指针旋转的轴:
默认是以每个指针的中心为轴旋转,不符合要求。
使用transform-origin
来改变旋转的轴
时间的获取:
使用new Date()
创建时间对象。并且通过date.getSeconds() | data.getMinutes() | data.getHours()
等方法获取当前时间对应的时、分、秒数。通过简单的数学计算得到当前时间各个指针对应的角度。
实现:
HTML结构:
<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 class="center"></div>
</div>
</div>
CSS样式:
html {
background:#018DED url(background.jpg);
background-size:cover;
font-family:'helvetica neue';
text-align: center;
font-size: 10px;
}
body {
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); /* account for the height of the clock hands */
}
.hand,.center {
width:50%;
height:6px;
background:black;
position: absolute;
top:50%;
/*transform-origin这个样式是用来与rotate样式配合,控制旋转中心的
*设置为transiform-origin:100% 100%;表示以元素右下角为旋转中心
* transiform-origin:100% 50%,以最右边中点为轴。
*/
transform-origin:100% 50%;
transition:all 0.05s;
border-radius:6px
}
.second-hand{
height: 3px;
background-color: red;
}
.min-hand{
background: white;
height: 8px;
}
.hour-hand{
background-color: white;
height: 10px;
width: 12rem;
left: 3rem;
}
.center{
width: 20px;
height: 20px;
background-color: #9Ebccc;
left: 50%;
margin-left:-10px;
margin-top:-6px;
border-radius:50%;
}
JS代码:
const secondHand = document.querySelector(".second-hand");
const minHand = document.querySelector(".min-hand");
const hourHand = document.querySelector(".hour-hand");
function setTime(){
const date = new Date();
const seconds = date.getSeconds();
const secondDegree = (seconds/60)*360 + 90;
// console.log("secondes:", seconds); 48 会直接得到相应的秒数不用转换
secondHand.style.transform = `rotate(${secondDegree}deg)`;
const minutes = date.getMinutes();
const minsDegree = (minutes/60)*360 + 90;
// console.log("minutes:", minutes); 55
minHand.style.transform = `rotate(${minsDegree}deg)`;
const hours = date.getHours();
const hoursDegree = (hours/60)*360 + 90;
// console.log("hours:", hours); 15
hourHand.style.transform = `rotate(${hoursDegree}deg)`;
}
setInterval(setTime,1000);
// setInterval的第一次执行是要在一秒以后的
setTime();
重点;
- new Date()
- date.getSeconds()
- date.getMinutes()
- date.getHours()
- transform:rotate(90deg)
- transform-origin:100%;
- border-radius
- setInterval(callback,1000)回调函数在1s后才开始执行