使用CSS和Js实现时钟效果
程序员文章站
2022-03-09 09:04:42
...
- 通过div和CSS构建时钟的表盘和指针
- 通过CSS动画实现指针跳动效果
-
通过js获取时间,并设置初始值
效果如图所示:
具体代码如下
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title> 使用CSS和Js实现时钟 </title>
<style>
.clock{width:400px;height:400px;margin:200px auto;position:relative;}
.clock_pan{width:396px;height:396px;border:2px solid #000;border-radius:50%;position:absolute;top:2px;left:2px;}
.clock_ge{height:380px;background:#000;position:absolute;top:8px;left:50%;transform-origin:0 50%;}
.clock_ge-0{width:4px;transform:rotate(0deg) translateX(-50%);z-index:2;}
.clock_ge-1{width:2px;transform:rotate(30deg) translateX(-50%);}
.clock_ge-2{width:2px;transform:rotate(60deg) translateX(-50%);}
.clock_ge-3{width:4px;transform:rotate(90deg) translateX(-50%);z-index:2;}
.clock_ge-4{width:2px;transform:rotate(120deg)translateX(-50%);}
.clock_ge-5{width:2px;transform:rotate(150deg) translateX(-50%);}
.clock_short{position:absolute;width:340px;height:340px;background:#fff;border-radius:50%;top:30px;left:30px;}
.clock_long{position:absolute;width:300px;height:300px;background:#fff;border-radius:50%;top:50px;left:50px;z-index:3;}
.clock_zhen{position:absolute;z-index:4;top:50%;left:50%;transform-origin:50% 100%;}
/* 通过设置animation-duration的不同时间,达到不同指针的效果*/
.clock_hour{width:6px;height:100px;background:#000;animation:clockrotate 43200s linear infinite;}
.clock_minute{width:4px;height:120px;background:#ff0;animation:clockrotate 3600s linear infinite;}
/* 通过animation-timing-function:steps(60,start) 达到秒针跳动的效果 */
.clock_second{width:2px;height:150px;background:#f00;animation:clockrotate 60s steps(60,start) infinite;}
@keyframes clockrotate{
0%{transform:translate(-50%,-100%) rotate(0deg);}
100%{transform:translate(-50%,-100%) rotate(360deg);}
}
</style>
</head>
<body>
<div class="clock">
<!-- 构建表盘 -->
<div class="clock_pan">
<!-- 设置刻度 -->
<div class="clock_ge clock_ge-0"> </div>
<div class="clock_ge clock_ge-1"> </div>
<div class="clock_ge clock_ge-2"> </div>
<div class="clock_ge clock_ge-3"> </div>
<div class="clock_ge clock_ge-4"> </div>
<div class="clock_ge clock_ge-5"> </div>
</div>
<!-- 通过2层遮盖,设置表盘上的刻度 -->
<div class="clock_short"> </div>
<div class="clock_long"> </div>
<!-- /构建表盘 -->
<!-- 构建指针 -->
<div class="clock_zhen clock_hour"> </div>
<div class="clock_zhen clock_minute"> </div>
<div class="clock_zhen clock_second"> </div>
<!-- /构建指针 -->
</div>
<script>
//通过Date()对象获取当前时间
var odate = new Date();
var seconds = odate.getSeconds();
var miniutes = odate.getMinutes();
var hour = odate.getHours();
//通过设置animation-delay为负值,使动画马上开始,跳过设置秒数进入动画。
document.querySelector('.clock_hour').style.animationDelay = -(hour * 3600 + miniutes * 60 + seconds) + 's';
document.querySelector('.clock_minute').style.animationDelay = -(miniutes * 60 + seconds) + 's';
document.querySelector('.clock_second').style.animationDelay = -(seconds) + 's';
</script>
</body>
</html>