網易前端面試真題之:使用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

相關文章
相關標籤/搜索