前端每日實戰:42# 視頻演示如何用純 CSS 創做一個均衡器 loader 動畫

圖片描述

效果預覽

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

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

可交互視頻教程

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

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

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

源代碼下載

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

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

代碼解讀

定義 dom,容器中包含 5 個子元素:flex

<div class="equalizer">
    <span></span>
    <span></span>
    <span></span>
    <span></span>
    <span></span>
</div>

居中顯示:動畫

body {
    margin: 0;
    height: 100vh;
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: black;
}

定義均衡器的樣式:spa

.equalizer {
    width: 10em;
    height: 10em;
    display: flex;
    justify-content: space-between;
}

.equalizer span {
    width: 1.5em;
    background: linear-gradient(0deg, green, yellow, red);
}

定義均衡器豎條的動畫效果:

.equalizer span {
    animation: up-and-down 2s linear infinite;
}

@keyframes up-and-down{
    0%, 100% {
        clip-path: inset(27% 0 0 0);
    }

    10% {
        clip-path: inset(17% 0 0 0);
    }

    20% {
        clip-path: inset(55% 0 0 0);
    }

    30% {
        clip-path: inset(30% 0 0 0);
    }

    40% {
        clip-path: inset(13% 0 0 0);
    }

    50% {
        clip-path: inset(38% 0 0 0);
    }

    60% {
        clip-path: inset(80% 0 0 0);
    }

    70% {
        clip-path: inset(21% 0 0 0);
    }

    80% {
        clip-path: inset(0% 0 0 0);
    }

    90% {
        clip-path: inset(36% 0 0 0);
    }
}

最後,設置各豎條依次動畫:

.equalizer span {
    animation: up-and-down 2s linear infinite calc(-1 * 0.4s * (var(--n) - 1));
}

.equalizer span:nth-child(1) {
    --n: 1;
}

.equalizer span:nth-child(2) {
    --n: 2;
}

.equalizer span:nth-child(3) {
    --n: 3;
}

.equalizer span:nth-child(4) {
    --n: 4;
}

.equalizer span:nth-child(5) {
    --n: 5;
}

大功告成!

相關文章
相關標籤/搜索