定義 dom,容器中包含左拍、小球和右拍:
<p class="court"> <p class="left-paddle"></p> <p class="ball"></p> <p class="right-paddle"></p> </p>
居中顯示:
body { height: 100vh; display: flex; align-items: center; justify-content: center; background: linear-gradient(silver, dimgray); }
調整盒模型:
* { 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; }
大功告成!
相信看了本文案例你已經掌握了方法,更多精彩請關注Gxl網其它相關文章!
推薦閱讀:
Chart.js輕量級圖表庫使用案例解析
Node.js中https使用案例解析
聲明:本網頁內容旨在傳播知識,若有侵權等問題請及時與本網聯系,我們將在第一時間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com