时钟小项目
继上一个摩天轮的小项目,这次则是在学习了一点JS的基础之下做一个随时间戳变的时钟
开始的开始,肯定是要先获取现在的时间戳,秒时分等
var time = new Date(), s = time.getSeconds(), m = time.getMinutes(), h = time.getHours()
再一个重要的点便是,如何让这个指针转起来,而且是要实时地转,而不是一分钟或者一小时转一下,涉及到旋转角度的问题,以及时间的换算。
正常的时间换算成x.x分钟或者x.x小时等
再加上一个旋转的角度
miao.style.transform = 'rotate(' + s * 6 + 'deg)' fen.style.transform = 'rotate(' + (m + s / 60) * 6 + 'deg)' shi.style.transform = 'rotate(' + (h + m / 60 + s / 3600) * 30 + 'deg)'
刷新一下,发现是否随时间转动
最后的最后,则是加一张背景图,设置div成为指针以及定位,便OK了。
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Titletitle>
<style>
#box {
width: 225px;
height: 225px;
background: url("img/clock.jpg") no-repeat;
position: relative;
margin: 100px auto 0;
background-position: -33px -8px;
border-radius: 50%
}
#dian {
width: 2px;
height: 2px;
background: green;
position: absolute;
top: 112px;
left: 112px
}
#shi {
width: 6px;
height: 60px;
background: #000;
position: absolute;
left: 110px;
top: 70px;
transform-origin: 50% 72%
}
#fen {
width: 4px;
height: 80px;
position: absolute;
left: 111px;
top: 50px;
background: #000;
transform-origin: 50% 79%
}
#miao {
width: 2px;
height: 100px;
position: absolute;
left: 112px;
top: 40px;
background: red;
transform-origin: 50% 73%;
}
style>
head>
<body>
<div id="box">
<div id="shi">div>
<div id="fen">div>
<div id="miao">div>
<div id="dian">div>
div>
body>
html>
<script>
var shi = document.getElementById('shi'),
fen = document.getElementById('fen'),
miao = document.getElementById('miao')
function clock() {
var time = new Date(),
s = time.getSeconds(),
m = time.getMinutes(),
h = time.getHours()
miao.style.transform = 'rotate(' + s * 6 + 'deg)'
fen.style.transform = 'rotate(' + (m + s / 60) * 6 + 'deg)'
shi.style.transform = 'rotate(' + (h + m / 60 + s / 3600) * 30 + 'deg)'
}
clock()
setInterval(clock, 1000)
script>