纯CSS做旋转不断的效果

10,482 阅读1分钟

这是我参与8月更文挑战的第5天,活动详情查看:8月更文挑战

昨天学习了CSS的animation动画特性,做了一个简单的放大字体效果。

文章链接如下:juejin.cn/post/699250…

今天学习一个不太熟悉的CSS属性:transform。

MDN官方文档:developer.mozilla.org/zh-CN/docs/…

transform属性允许你旋转,缩放,倾斜或平移给定元素。这是通过修改CSS视觉格式化模型的坐标空间来实现的。

其中可选得转换样式被称为transform-functionsMDN文档中关于transform-functions,列举了包括matrix, matrix3d, perspective, rotate等多个函数。

本文会用到上一篇文章中介绍的animation以及transform中的rotate函数。

其中有几个关键点值得注意

  1. animation属性值中的速度设置为linear。表示动画变化是匀速的。 如果是默认的ease,即默认逐渐变慢的速度时,可以看到动画在转换为25%,50%,75%时会有比较明显的卡顿效果。这也帮助我们理解了animation中的速度函数,是针对@keyframes中的每一段的,而不是从开始到结束的,若采用ease默认值,效果如下所示:

35e414a4-a38d-46e1-834f-9b60dd2ae3e7.gif

  1. animation属性中的定义播放次数为:infinate,表示无限次数播放,从而可以使动画一直循环播放。

最终的播放效果如下图所示:

808c465f-8ff0-4697-a941-684e72aa5c72.gif

<!DOCTYPE html>

<body class="border">
    <div class="rotate">
        中国加油!奥运健儿加油!
    </div>
</body>
<style>
    .border {
        border: 1px solid black;
    }
    body {
        height: 100vh;
        width: 100%;
        display: flex;
        flex-direction: row;
        align-items: center;
        justify-content: center;
    }

    .rotate {
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 50px;
        color: red;
        animation: rotate 10s linear infinite;
        -webkit-animation: rotate 10s linear infinite;
        
    }

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

        25% {
            transform: rotate(90deg);
        }

        50% {
            transform: rotate(180deg);
        }

        75% {
            transform: rotate(270deg);
        }

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

    @-webkit-keyframes rotate {
        0% {
            transform: rotate(0);
        }

        25% {
            transform: rotate(90deg);
        }

        50% {
            transform: rotate(180deg);
        }

        75% {
            transform: rotate(270deg);
        }

        100% {
            transform: rotate(360deg);
        }
    }
</style>

</html>

PS: 制作动画所用软件为ScreenToGif。