按下右側的「點擊預覽」按鈕能夠在當前頁面預覽,點擊連接能夠全屏預覽。css
https://codepen.io/comehope/pen/RBLWzJhtml
此視頻是能夠交互的,你能夠隨時暫停視頻,編輯視頻中的代碼。前端
請用 chrome, safari, edge 打開觀看。git
https://scrimba.com/p/pEgDAM/cawN3f9github
每日前端實戰系列的所有源代碼請從 github 下載:chrome
https://github.com/comehope/front-end-daily-challengesdom
定義 dom,容器中包含 2 個元素,train
表明火車,track
表明鐵軌,其中包含的 3 個 <span>
表明 3 根枕木。flex
<div class="loader"> <div class="train"></div> <div class="track"> <span></span> <span></span> <span></span> </div> </div>
居中顯示:動畫
body{ margin: 0; height: 100vh; display: flex; align-items: center; justify-content: center; background: linear-gradient(#666, #333); }
定義容器尺寸:spa
.loader { width: 8em; height: 10em; font-size: 20px; }
先畫火車。
畫出火車的輪廓:
.train { width: 6em; height: 6em; color: #444; background: #bbb4ab; border-radius: 1em; position: relative; left: 1em; }
用 ::before 僞元素畫出車窗:
.train::before { content: ''; position: absolute; width: 80%; height: 2.3em; background-color: currentColor; border-radius: 0.4em; top: 1.2em; left: 10%; }
再用 ::after 僞元素畫出車窗上的信號燈:
.train::after { content: ''; position: absolute; width: 25%; height: 0.4em; background-color: currentColor; border-radius: 0.3em; top: 0.4em; left: calc((100% - 25%) / 2); }
利用徑向漸變畫出車燈:
.train { background: radial-gradient(circle at 20% 80%, currentColor 0.6em, transparent 0.6em), radial-gradient(circle at 80% 80%, currentColor 0.6em, transparent 0.6em), #bbb; }
接下來畫鐵軌和枕木。
定義鐵軌的寬度,比火車稍寬:
.track { width: 8em; }
用僞元素畫出鐵軌:
.track { position: relative; } .track::before, .track::after { content: ''; position: absolute; width: 0.3em; height: 4em; background-color: #bbb; border-radius: 0.4em; }
把鐵軌分別放置在兩側,並造成近大遠小的視覺效果:
.track::before, .track::after { transform-origin: bottom; } .track::before { left: 0; transform: skewX(-27deg); } .track::after { right: 0; transform: skewX(27deg); }
畫出枕木,這是距離觀察者最近的效果,目前 3 根枕木是重疊在一塊兒的:
.track span { width: inherit; height: 0.3em; background-color: #bbb; position: absolute; top: 4em; }
設置鐵軌的動畫效果:
.track span { animation: track-animate 1s linear infinite; } @keyframes track-animate { 0% { transform: translateY(-0.5em) scaleX(0.9); filter: opacity(0); } 10%, 90% { filter: opacity(1); } 100% { transform: translateY(-4em) scaleX(0.5); filter: opacity(0); } }
爲另外 2 根枕木設置動畫延時,使鐵軌看起來就像永遠走不完的樣子:
.track span:nth-child(2) { animation-delay: -0.33s; } .track span:nth-child(3) { animation-delay: -0.66s; }
最後,爲火車增長動畫效果,看起來就像在行駛中微微晃動:
.train { animation: train-animate 1.5s infinite ease-in-out; } @keyframes train-animate { 0%, 100% { transform: rotate(0deg); } 25%, 75% { transform: rotate(0.5deg); } 50% { transform: rotate(-0.5deg); } }
大功告成!