网易前端面试真题之:使用css实现“钟摆”效果
前不久,去网易面试,面试官出了一道css动画相关的面试题,这里分享给大家。
实现效果
![822ae2eaa7a5ca1500de30346dcaa459.gif](https://i-blog.csdnimg.cn/blog_migrate/3bf85f60befe06d3ac01f6fad782e14d.gif)
CSS实现钟摆效果
前置知识
动画是使元素从一种样式逐渐变化为另一种样式的效果。
- 属性描述
- @keyframes规定动画
- animation所有动画属性的简写属性,除了 animation-play-state 属性。
- animation-name规定 @keyframes 动画的名称。
- animation-duration规定动画完成一个周期所花费的秒或毫秒。默认是 0。
- animation-timing-function规定动画的速度曲线。默认是 "ease"。
- animation-delay规定动画何时开始。默认是 0。
- animation-iteration-count规定动画被播放的次数。默认是 1。
- animation-direction规定动画是否在下一周期逆向地播放。默认是 "normal"。
- animation-play-state规定动画是否正在运行或暂停。默认是 "running"。
- animation-fill-mode规定对象动画时间之外的状态。
思路
- 创建HTML5基本模板
CSS钟摆
- 创建动画
.line{width: 20px;height: 400px;background: red;margin: 50px auto; transform-origin: center top; animation: swing 5s; animation-iteration-count:infinite; animation-timing-function: linear; position: relative;}@keyframes swing {0%{transform:rotate(45deg);}25%{transform:rotate(0deg);}50%{transform:rotate(-45deg);}75%{transform:rotate(0deg);}100%{transform:rotate(45deg);}}
解决办法
- 属性解释
transform-origin: center top;// 这里指定起始点为居中,靠上animation: swing 5s;// 指定动画的名称,与整个动画的时间animation-iteration-count:infinite;//设置无限摆动animation-timing-function: linear;//指定运行的速度曲线,liner表示线性的,即匀速。
- @keyframes讲解
transform:rotate(45deg);//表示变换的动作为旋转45度
源码
- 源码汇总
钟摆