js实用小程序——时钟
用js可以做许多有趣的小动画,下面是一个简易时钟的小例子,可能样式写的有点多了,下方最终效果图(作为老司机的我有点小完美的强迫症哈哈哈...)
<!DOCTYPE html>
<html>
<head>
<title>时钟</title>
<meta charset = "utf-8">
<style type="text/css">
span{
margin: 0;
padding: 0;
}
#box{
width: 600px;
height: 600px;
border: 1px solid rgb(99,99,99);
border-radius: 50%;
margin: 50px auto;
position: relative;
background: rgb(155,155,155);
box-shadow: 0 0 20px rgb(99,99,99);
}
#round{
width: 540px;
height: 540px;
border: 1px solid rgb(99,99,99);
border-radius: 50%;
position: absolute;
top: 30px;
left: 30px;
box-shadow: 0 0 20px rgb(99,99,99) inset;
}
#round span{
color: white;
font-size: 50px;
position: absolute;
}
#L{
left: 242px;
top: 10px;
}
#F{
left: 254px;
bottom: 10px;
}
#I{
left: 10px;
top: 248px;
}
#C{
right: 10px;
bottom: 242px;
}
#A{
right: 130px;
top: 45px;
}
#B{
right: 45px;
top: 130px;
}
#D{
right: 45px;
bottom: 130px;
}
#E{
right: 130px;
bottom: 45px;
}
#K{
left: 130px;
top: 45px;
}
#J{
left: 45px;
top: 130px;
}
#H{
left: 45px;
bottom: 130px;
}
#G{
left: 130px;
bottom: 45px;
}
#down{
width: 40px;
height: 40px;
background: rgb(39,39,39);
border-radius: 50%;
position: absolute;
left: 250px;
top: 250px;
}
#sec{
width: 240px;
height: 3px;
background: red;
position: absolute;
left: 240px;
top: 269px;
transform-origin: 31px;
}
#min{
width: 220px;
height: 8px;
background: rgb(67,91,32);
position: absolute;
left: 240px;
top: 266px;
transform-origin: 31px;
}
#hour{
width: 190px;
height: 12px;
background: rgb(200,20,24);
position: absolute;
left: 240px;
top: 264px;
transform-origin: 31px;
}
#up{
width: 20px;
height: 20px;
background: white;
border-radius: 50%;
position: absolute;
left: 260px;
top: 260px;
}
</style>
</head>
<body>
<div id="box">
<div id="round">
<span id="A">1</span>
<span id="B">2</span>
<span id="C">3</span>
<span id="D">4</span>
<span id="E">5</span>
<span id="F">6</span>
<span id="G">7</span>
<span id="H">8</span>
<span id="I">9</span>
<span id="J">10</span>
<span id="K">11</span>
<span id="L">12</span>
<div id="down"></div>
<div id="sec"></div>
<div id="min"></div>
<div id="hour"></div>
<div id="up"></div>
</div>
<script type="text/javascript">
// 获取元素
var hour = document.getElementById('hour');
var min = document.getElementById('min');
var sec = document.getElementById('sec');
// 定义刷新函数
function fresh(){
// 获取此刻的时间
var date = new Date();
var sec2 = date.getSeconds();
var min2 = date .getMinutes();
var hour2 = date . getHours();
// 12时制转换
hour2 = hour2 > 12 ? hour2 - 12 : hour2;
// 秒针 1s转过的角度为6度,因为起始位置在3点处,需要减去90度。
var s = sec2 * 6 - 90;
sec.style.transform = 'rotate('+ s + 'deg)';
// 分针 让分针随秒针的旋转而旋转
var a = sec2 /60 * 6;
var b = min2 * 6 - 90;
var c = a + b;
min.style.transform = 'rotate('+ c + 'deg)';
// 时针 让时针随分针的旋转而旋转
var d = min2 / 60 * 30;
var e = hour2 * 30 - 90;
var f = d + e;
hour.style.transform = 'rotate('+ f + 'deg)';
}
fresh();
//每隔1s刷新一次
setInterval(function () {
fresh();
},1000);
</script>
</div>
</body>
</html>