前不久,去网易面试,面试官出了一道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基本模板
<!DOCTYPE html>
<html lang="en">
<head>
<title>CSS钟摆</title>
</head>
<body>
</body>
</html>
- 创建动画
.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度
源码
源码汇总
<!DOCTYPE html>
<html>
<head>
<title>钟摆</title>
</head>
<style>
.container{
width: 100%;
}
.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;
}
.ball{
width: 60px;
height: 60px;
border-radius: 30px;
background: blue;
position: absolute;
bottom: -60px;
left: -20px;
}
@keyframes swing {
0%{
transform:rotate(45deg);
}
25%{
transform:rotate(0deg);
}
50%{
transform:rotate(-45deg);
}
75%{
transform:rotate(0deg);
}
100%{
transform:rotate(45deg);
}
}
</style>
<body>
<div class="container">
<div class="line">
<div class="ball"></div>
</div>
</div>
</body>
</html>
欢迎大家关注我的微信公众号“IT男真会玩”。