网易前端面试真题之:使用CSS实现“钟摆”效果。

前不久,去网易面试,面试官出了一道css动画相关的面试题,这里分享给你们。javascript

实现效果

image

前置知识

动画是使元素从一种样式逐渐变化为另外一种样式的效果。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度
复制代码

源码

源码汇总html

<!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男真会玩”。html5

相关文章
相关标签/搜索