利用JavaScript结合css定位和transform属性实现一个HTML在线时钟。
1、根据当前的系统时间,精确到秒显示时间;
2、模拟正常的钟表走时效果,每一秒秒针走一小格;
3、分针每一分钟走一小格;
4、时针不能直接每一小时走一大格,而是模拟每分钟都转动一点点角度的真实效果。
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>在线时钟</title>
<style>
#face {
width: 600px;
height: 600px;
margin: 20px auto;
background: url("../image/clockface.jpg") no-repeat;
position: relative;
}
#second {
width: 4px;
height: 200px;
background-color: #FC5753;
position: absolute;
left: 298px;
top: 100px;
/* 设置指针的旋转基点为下方中间位置 */
transform-origin: bottom center;
}
#minute {
width: 10px;
height: 175px;
background-color: #0e2218;
position: absolute;
left: 295px;
top: 125px;
transform-origin: bottom center;
}
#hour {
width: 15px;
height: 150px;
background-color: #5948ff;
position: absolute;
left: 292px;
top: 150px;
transform-origin: bottom center;
}
#center {
width: 30px;
height: 30px;
background-color: black;
position: absolute;
left: 285px;
top: 285px;
border-radius: 50%;
}
</style>
</head>
<body>
<div id="face">
<div id="hour"></div> <!-- 时针 -->
<div id="minute"></div> <!-- 分针 -->
<div id="second"></div> <!-- 秒针 -->
<div id="center"></div> <!-- 中心的小圆点 -->
</div>
</body>
<script>
setInterval(function() {
var time = new Date();
var second = time.getSeconds();
var minute = time.getMinutes();
var hour = time.getHours();
var hourDeg = hour%12*30 + minute*0.5;
document.getElementById("second").style.transform = "rotate(" + second*6 + "deg)";
document.getElementById("minute").style.transform = "rotate(" + minute*6 + "deg)";
document.getElementById("hour").style.transform = "rotate(" + hourDeg + "deg)";
}, 1000);
</script>
</html>