前端每日實戰:85# 視頻演示如何用純 CSS 創做一個小球反彈的動畫

圖片描述

效果預覽

按下右側的「點擊預覽」按鈕能夠在當前頁面預覽,點擊連接能夠全屏預覽。css

https://codepen.io/comehope/pen/OwWROOhtml

可交互視頻

此視頻是能夠交互的,你能夠隨時暫停視頻,編輯視頻中的代碼。前端

請用 chrome, safari, edge 打開觀看。git

https://scrimba.com/p/pEgDAM/cnKwKA3github

源代碼下載

每日前端實戰系列的所有源代碼請從 github 下載:chrome

https://github.com/comehope/front-end-daily-challengesdom

代碼解讀

定義 dom,只有 1 個元素:flex

<div class="box"></div>

居中顯示:動畫

body {
    margin: 0;
    height: 100vh;
    display: flex;
    align-items: center;
    justify-content: center;
    background: linear-gradient(#666, #333);
}

定義容器尺寸:spa

.box {
    width: 30em;
    height: 20em;
    font-size: 10px;
    background-color: steelblue;
    border: 0.5em solid #222;
}

用僞元素畫出小球:

.box {
    position: relative;
}

.box::before {
    content: '';
    position: absolute;
    width: 2em;
    height: 2em;
    background-color: silver;
    border-radius: 50%;
    box-shadow: inset -0.3em -0.3em 0.5em rgba(0, 0, 0, 0.6);
}

定義沿 x 軸即橫向移動的動畫效果:

@keyframes moveX {
    from {
        left: 0;
    }

    to {
        left: calc(30em - 2em);
    }
}

定義沿 y 軸即縱向移動的動畫效果:

@keyframes moveY {
    from {
        top: 0;
    }

    to {
        top: calc(20em - 2em);
    }
}

最後,把動畫效果應用到小球上:

.box::before {
    animation: 
        moveX 2s linear infinite alternate,
        moveY 2.5s linear infinite alternate;
}

大功告成!

相關文章
相關標籤/搜索