按下右側的「點擊預覽」按鈕能夠在當前頁面預覽,點擊連接能夠全屏預覽。css
https://codepen.io/comehope/pen/rvgLzKhtml
此視頻是能夠交互的,你能夠隨時暫停視頻,編輯視頻中的代碼。前端
請用 chrome, safari, edge 打開觀看。git
https://scrimba.com/p/pEgDAM/cW7gZfbgithub
每日前端實戰系列的所有源代碼請從 github 下載:chrome
https://github.com/comehope/front-end-daily-challengesdom
定義 dom,容器中包含左拍、小球和右拍:flex
<div class="court"> <div class="left-paddle"></div> <div class="ball"></div> <div class="right-paddle"></div> </div>
居中顯示:spa
body { height: 100vh; display: flex; align-items: center; justify-content: center; background: linear-gradient(silver, dimgray); }
調整盒模型:code
* { box-sizing: border-box; }
畫出球案:
.court { width: 20em; height: 20em; color: white; border: 1em solid currentColor; }
畫出左拍:
.court { position: relative; } .left-paddle width: 1em; height: calc(50% - 1em); background-color: currentColor; position: absolute; top: 1em; left: 1em; }
讓左拍動起來:
.left-paddle { animation: left-moving 1s linear infinite alternate; } @keyframes left-moving { to { transform: translateY(100%); } }
相似地,畫出右拍:
.right-paddle width: 1em; height: calc(50% - 1em); background-color: currentColor; position: absolute; top: 1em; left: 1em; bottom: 1em; right: 1em; }
相似地,讓右拍動起來:
.right-paddle { animation: right-moving 1s linear infinite alternate; } @keyframes right-moving { to { transform: translateY(-100%); } }
畫出小球:
.ball { width: 100%; height: 1em; border-left: 1em solid currentColor; position: absolute; left: 2em; top: calc(50% - 1.5em); }
讓小球動起來:
.ball { animation: bounce 1s linear infinite alternate; } @keyframes bounce { to { left: calc(100% - 3em); } }
最後,重構一下左右拍的代碼,合併共有屬性:
.left-paddle, .right-paddle { width: 1em; height: calc(50% - 1em); background-color: currentColor; position: absolute; animation: 1s linear infinite alternate; } .left-paddle { top: 1em; left: 1em; animation-name: left-moving; } .right-paddle { bottom: 1em; right: 1em; animation-name: right-moving; }
大功告成!