前段时间发的五子棋的游戏很多小伙伴都私聊让再做个, 今天小猿圈 web 前端讲师为大家分享的是 CSS3 动画练习案例: 用 CSS3 做个钟表, 想玩的小伙伴记得自己运行一下呦.
自学 CSS3 属性之后, 我们来用一个小案例进行一个综合练习, 这个案例主要是动画的应用, 我们就用纯 CSS 动画做一个能走字的钟表.
首先我们来准备 html 来布局一下:
- <body>
- <div class="clock">
- <div class="line1">
- </div>
- <div class="line2">
- </div>
- <div class="line3">
- </div>
- <div class="line4">
- </div>
- <div class="line5">
- </div>
- <div class="line6">
- </div>
- <div class="cent">
- </div>
- <div class="cover">
- </div>
- <div class="hour">
- </div>
- <div class="minute">
- </div>
- <div class="seconds">
- </div>
- </div>
- </body>
布局很简单, 六根直线通过旋转一定角度做刻度一个中间小圆点, 一个遮罩来盖住六根直线的中间部分, 使直线变成刻度, 后面三个是时分秒针.
下面通过 CSS 把钟表的大概样子设置出来.
- .clock {
- /* 创建圆形盒子当做表盘 */
- width: 200px;
- height: 200px;
- margin: 100px auto;
- position: relative;
- border: 10px solid #000;
- border-radius: 50%;
- }
- .clock div:nth-child(-n+6) {
- /* 选中前 6 个子元素做出 6 条线当做表的刻度 */
- width: 6px;
- height: 200px;
- background-color: #aaa;
- position: absolute;
- left: 50%;
- margin-left:-3px;
- }
- /* 让 6 条线递增旋转 30 度 */
- .clock div:nth-child(1) {
- transform: rotate(30deg);
- }
- .clock div:nth-child(2) {
- transform: rotate(60deg);
- }
- .clock div:nth-child(3) {
- transform: rotate(90deg);
- background-color: #333;
- }
- .clock div:nth-child(4) {
- transform: rotate(120deg);
- }
- .clock div:nth-child(5) {
- transform: rotate(150deg);
- }
- .clock div:nth-child(6) {
- transform: rotate(0deg);
- background-color: #333;
- }
- /* 中心小圆点 */
- .cent {
- width: 20px;
- height: 20px;
- background-color: #000;
- border-radius: 50%;
- position:absolute;
- z-index: 3;
- left: 50%;
- top:50%;
- margin: -10px 0 0 -10px;
- z-index:2;
- }
- /* 遮住线的中间部分, 让线成为刻度 */
- .cover {
- width: 180px;
- height: 180px;
- border-radius: 50%;
- background-color: #fff;
- position:absolute;
- left: 50%;
- top:50%;
- margin:-90px 0 0 -90px;
- }
后面加上中心圆点和遮罩, 让它看起来像个表盘.
接下来我们就可以准备表针和动画了.
- /* 时针制作 */
- .hour {
- width: 6px;
- height: 50px;
- background-color: #000;
- position:absolute;
- left: 50%;
- top:100px;
- margin-left: -3px;
- animation: clockrotate 43200s steps(43200) infinite linear;
- transform-origin: top center;
- }
- /* 分针制作 */
- .minute {
- width: 60px;
- height: 6px;
- background-color: #555;
- position:absolute;
- left:40px;
- top:50%;
- margin-top: -3px;
- animation: clockrotate 3600s steps(3600) infinite;
- transform-origin: center right;
- }
- /* 秒针制作 */
- .seconds {
- width: 4px;
- height: 70px;
- background-color:red;
- position: absolute;
- left:50%;
- top:30px;
- margin-left: -2px;
- animation: clockrotate 60s steps(60) infinite ;
- transform-origin: bottom center;
- }
- /* 设置动画序列 */
- @keyframes clockrotate {
- form{
- }
- to {
- transform: rotate(360deg);
- }
- }
设置每个针的动画是旋转 360 度, 根据时, 分, 秒来计算动画执行完毕需要的时间和步数, 加个 infinite 无限执行, 另外还要注意表针旋转的中心点设置.
上述就是小猿圈老师针对 CSS3 动画练习案例: 用 CSS3 做个钟表介绍, 相信你对 Web 前端也是有一定的了解的 Web 前端自学2群: 738735873, 如果遇到不会的问题可以到小猿圈去寻找答案的, 里面有最新最全面的视频教程等你来学习, 只要你想学习编程这里都有.
来源: http://www.jianshu.com/p/92cfa1474f72