且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何用纯 CSS 创作一个没有 DOM 元素的动画

更新时间:2022-01-31 12:00:49

如何用纯 CSS 创作一个没有 DOM 元素的动画

效果预览

在线演示

按下右侧的“点击预览”按钮可以在当前页面预览,点击链接可以全屏预览。

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

可交互视频

此视频是可以交互的,你可以随时暂停视频,编辑视频中的代码。

请用 chrome, safari, edge 打开观看。

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

源代码下载

本地下载

每日前端实战系列的全部源代码请从 github 下载:

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

代码解读

没有 dom 元素,直接写 css。
设置页面空间:


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

用伪元素设置背景图案:


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);
    }
}

大功告成!

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