1. 程式人生 > >如何用純 CSS 創作炫酷的同心矩形旋轉動畫

如何用純 CSS 創作炫酷的同心矩形旋轉動畫

效果預覽

線上演示

按下右側的“點選預覽”按鈕可以在當前頁面預覽,點選連結可以全屏預覽。

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

可互動視訊教程

此視訊是可以互動的,你可以隨時暫停視訊,編輯視訊中的程式碼。

請用 chrome, safari, edge 開啟觀看。

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

原始碼下載

本地下載

請從 github 下載。

https://github.com/comehope/front-end-daily-challenges/tree/master/017-swapping-colors-loader-animation

程式碼解讀

定義 dom,一個容器中包含一個 span:

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

居中顯示:

html,
body,
.loader {
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: black;
}

設定 span 的樣式:

.loader {
    width: 10em;
    height: 10em;
    font-size: 28px;
    position: relative;
}

.loader span {
    position: absolute;
    width: 100%;
    height: 100%;
    background-color: rgba(100%, 0%, 0%, 0.3);
    box-sizing: border-box;
    border: 0.5em solid;
    border-color: white rgba(100%, 100%, 100%, 0.2);
}

在 dom 中把 span 增加到 5 個:

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

分別設定 5 個 span 的尺寸:

.loader span:nth-child(1) {
    width: calc(20% + 20% * (5 - 1));
    height: calc(20% + 20% * (5 - 1));
}

.loader span:nth-child(2) {
    width: calc(20% + 20% * (5 - 2));
    height: calc(20% + 20% * (5 - 2));
}

.loader span:nth-child(3) {
    width: calc(20% + 20% * (5 - 3));
    height: calc(20% + 20% * (5 - 3));
}

.loader span:nth-child(4) {
    width: calc(20% + 20% * (5 - 4));
    height: calc(20% + 20% * (5 - 4));
}

.loader span:nth-child(5) {
    width: calc(20% + 20% * (5 - 5));
    height: calc(20% + 20% * (5 - 5));
}

增加顏色變幻的動畫效果:

.loader span {
    animation: animate 5s ease-in-out infinite alternate;
}

@keyframes animate {
    0% {
        /* red */
        background-color: rgba(100%, 0%, 0%, 0.3);
    }

    25% {
        /* yellow */
        background-color: rgba(100%, 100%, 0%, 0.3);
    }

    50% {
        /* green */
        background-color: rgba(0%, 100%, 0%, 0.3);
    }

    75% {
        /* blue */
        background-color: rgba(0%, 0%, 100%, 0.3);
    }

    100% {
        /* purple */
        background-color: rgba(100%, 0%, 100%, 0.3);
    }
}

再增加旋轉效果:

@keyframes animate {
    0% {
        transform: rotate(0deg);
    }

    100% {
        transform: rotate(720deg);
    }
}

最後,為每個 span 設定動畫延時,增加動感:

.loader span:nth-child(1) {
    animation-delay: calc(0.2s * (5 - 1));
}

.loader span:nth-child(2) {
    animation-delay: calc(0.2s * (5 - 2));
}

.loader span:nth-child(3) {
    animation-delay: calc(0.2s * (5 - 3));
}

.loader span:nth-child(4) {
    animation-delay: calc(0.2s * (5 - 4));
}

.loader span:nth-child(5) {
    animation-delay: calc(0.2s * (5 - 5));
}

知識點

原文地址:https://segmentfault.com/a/1190000014807564