学了一段时间的HTML、CSS和JS后,给大家做一款漂亮的不像实力派的HTML时钟,先看图:

涉及到的知识点有: CSS3动画、DOM操作、定时器、圆点坐标的计算(好多人是不是已经还给自己的老师了~)
接下来,我们用5步来制作它
step1、准备HTML
首先,我们需要准备HTML结构,背景、表盘、指针(时针、分针、秒针)、数字。
<div id="clock"> <div class="bg"> <div class="point"> <div id="hour"></div> <div id="minute"></div> <div id="second"></div> <div class="circle"></div> </div> </div> < /div>
step2、准备CSS
定义好指针的颜色和大小,需要说明的是transform: rotate(-90deg); 用来旋转指针,transform-origin:0 6px; 用来设置旋转中心点。
<style>
*{
margin: 0;
padding: 0;
}
#clock{
margin: 5% auto;
width: 400px;
height: 400px;
border-radius: 10px;
background: #aaa;
position: relative;
transform: rotate(-90deg);
}
#clock .bg{
width: 360px;
height: 360px;
border-radius: 50%;
background: #fff;
position: absolute;
left: 50%;
top: 50%;
margin-left: -180px;
margin-top: -180px;
}
#clock .point{
position: absolute;
left: 50%;
top: 50%;
margin-left: -14px;
margin-top: -14px;
}
#clock #hour{
width: 80px;
height: 16px;
background: #000;
margin: 6px 0 0 14px;
/*transform: rotate(30deg);*/
transform-origin:0 8px;
/*animation: hour 3s linear 100!* alternate*!;*/
border-radius: 16px;
}
#clock #minute{
width: 120px;
height: 12px;
background: #000;
margin: -14px 0 0 14px;
transform-origin:0 6px;
border-radius: 12px;
}
#clock #second{
width: 160px;
height: 6px;
background: #f00;
margin: -9px 0 0 14px;
transform-origin:0 3px;
border-radius: 6px;
}
#clock .point .circle{
width: 28px;
height: 28px;
border-radius: 50%;
background: #000;
position: absolute;
left: 0;
top: 0;
}
@keyframes hour {
from {transform: rotate(0deg);}
to {transform: rotate(360deg);}
}
#clock .number{
position: absolute;
font-size: 34px;
width: 50px;
height: 50px;
line-height: 50px;
text-align: center;
transform: rotate(90deg);
}
< /style>
step3、计算时针位置
JS通过Date对象获取当前时间,getHours获取小时、getMinutes获取分钟、getSeconds获取秒。时针转动一周是12格,每格角度就是360°/12,分钟和秒都是60格,每格角度360°/60。
function clock(){
var date = new Date();//获取当前时间
//时(0-23) 分(0-59)秒(0-59)
//计算转动角度
var hourDeg = date.getHours()*360/12;
var minuteDeg = date.getMinutes()*360/60;
var secondDeg = date.getSeconds()*360/60;
//console.log(hourDeg, minuteDeg, secondDeg);
//设置指针
hour.style.transform = 'rotate('+hourDeg+'deg)';
minute.style.transform = 'rotate('+minuteDeg+'deg)';
second.style.transform = 'rotate('+secondDeg+'deg)';
}
内容版权声明:除非注明,否则皆为本站原创文章。
