前端每日實戰:106# 視頻演示如何用純 CSS 創做一個沒有 DOM 元素的動畫

圖片描述

效果預覽

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

https://codepen.io/comehope/pen/JBqjqm前端

可交互視頻

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

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

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

源代碼下載

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

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

代碼解讀

沒有 dom 元素,直接寫 css。
設置頁面空間:code

body {
    position: fixed;
    margin: 0;
    width: 100vw;
    height: 100vh;
}

用僞元素設置背景圖案:orm

body::before {
    content: '';
    position: fixed;
    width: 200vmax;
    height: 200vmax;
    background-color: steelblue;
    color: turquoise;
    background-image: 
        linear-gradient(
            45deg, 
            currentColor 25%, 
            transparent 25%, transparent 75%, 
            currentColor 75%),
        linear-gradient(
            45deg, 
            currentColor 25%, 
            transparent 25%, transparent 75%, 
            currentColor 75%);
    background-position: 0 0, 5vmax 5vmax;
    background-size: 10vmax 10vmax;

平移背景圖案:視頻

body::before {
    top: 50%;
    left: 50%;
    animation: 
        9s move infinite ease-in-out alternate;
}

@keyframes move {
    from {
        left: -40%;
        top: -40%;
    }

    to {
        left: -60%;
        top: -60%;
    }
}

讓背景圖案轉動起來:

body::before {
    animation: 
        9s move infinite ease-in-out alternate,
        9s -1.5s rotating infinite ease-in-out alternate;
}

@keyframes rotating {
    to {
        transform: rotate(180deg);
    }
}

平移頁面:

body {
    top: 50%;
    left: 50%;
    animation: 
        3s move infinite ease-in-out alternate;
}

縮放頁面:

body {
    animation: 
        3s move infinite ease-in-out alternate,
        3s zoom infinite ease-in-out alternate;
}

@keyframes zoom {
    to {
        transform: scale(10);
    }
}

最後,增長變色效果:

@keyframes rotating {
    to {
        transform: rotate(180deg);
        filter: hue-rotate(1turn);
    }
}

大功告成!

相關文章
相關標籤/搜索