四时宝库

程序员的知识宝库

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

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

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

实现效果

前置知识

动画是使元素从一种样式逐渐变化为另一种样式的效果。

  • 属性描述
  1. @keyframes规定动画
  2. animation所有动画属性的简写属性,除了 animation-play-state 属性。
  3. animation-name规定 @keyframes 动画的名称。
  4. animation-duration规定动画完成一个周期所花费的秒或毫秒。默认是 0。
  5. animation-timing-function规定动画的速度曲线。默认是 "ease"。
  6. animation-delay规定动画何时开始。默认是 0。
  7. animation-iteration-count规定动画被播放的次数。默认是 1。
  8. animation-direction规定动画是否在下一周期逆向地播放。默认是 "normal"。
  9. animation-play-state规定动画是否正在运行或暂停。默认是 "running"。
  10. 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>

发表评论:

控制面板
您好,欢迎到访网站!
  查看权限
网站分类
最新留言
    友情链接