写滚动动画不止方便一点点,CSS未来特性animation-timeline 介绍

浏览量:483

前言

今天来介绍一个全新的css 特性,虽然仍是实验性特性,兼容性差的不能提,但提前了解也非常有价值,因为它实在把滚动动画简化太多了。在实际项目中也可以使用polyfill: https://github.com/flackr/scroll-timeline

准备

有多新?
看看这一溜红叉:

即使你是最新版的Chrome/Firefox 也并不支持这一特性,需要手动开启实验性特性:

Firefox 进入 about:config, 将 layout.css.scroll-linked-animations.enabled 设为true

Chrome 进入chrome://flags

不然连demo 效果也看不了 o(╥﹏╥)o

滚动动画

稍微有经验的开发者会知道,滚动动画的原理其实很简单,即
监听滚动 -> 根据滚动位置改变元素状态
但这东西说起来简单,做起来复杂,采用命令式的控制方法来做的话,简单一些的还好说,需要操作的元素一多就乱套了,不但效果不好实现,出了问题更不好修复。
所以开发者通常使用一些库来实现效果。

常用工具

简单一点的有AOS: https://michalsnik.github.io/aos/
需要复杂效果的有 https://scrollrevealjs.org/api/reveal.html GSAP 等
GSAP 需要使用对应的ScrollTrigger plugins。
比如大疆的Mavic 3 介绍就是使用的GSAP: https://www.dji.com/cn/mavic-3?site=brandsite&from=homepage

但是,当css 原生支持后,不考虑兼容性的情况下,大部分我们都无需再引入库,而是直接定义属性即可快速出现效果。

用法

以MDN 的官方例子为例:

<div id="container"><div id="square"></div></div>
#container {
    height: 300px;
}

#square {
    background-color: deeppink;
    width: 100px;
    height: 100px;
    margin-top: 100px;
    animation-name: rotateAnimation;
    animation-duration: 3s;
    animation-direction: alternate;
    animation-timeline: squareTimeline;
}

@scroll-timeline squareTimeline {
    source:selector("#container");orientation:"vertical";scroll-offsets:0px,300px;
}

@keyframe srotateAnimation {
    from {
        transform: rotate(0deg);
    }

    to {
        transform: rotate(360deg);
    }
}

其中最关键的部分为:

animation-timeline

详细请参考: https://developer.mozilla.org/en-US/docs/Web/CSS/animation-timeline, 这里我们给予它的值是一个 scroll-timeline。

@scroll-timeline

它定义了指定元素的滚动动画rule,详细文档参考MDN: https://developer.mozilla.org/en-US/docs/Web/CSS/@scroll-timeline.
不太需要关注具体属性,当前的草案似乎已经被废弃。只需要声明scroll-timeline 即可,实测几项属性在最新版firefox 中几乎不再支持。
即这样也可运行:

 animation-timeline: squareTimeline;

@scroll-timeline squareTimeline {
}

codepen 实例效果

末尾

这注定是一个日常不太能使用到的新属性,甚至在浏览器正式支持前标准也会有些微的改动。
这篇文章也仅仅是对其的简单介绍,看完连写个小demo都要去打开浏览器的实验性特性。
但总会到那么一个时候,发现兼容性已经一眼绿,潇洒的加上属性实现效果,然后心里悄悄感慨,嘿,这搞的还真方便。
就像position: sticky 一样。

留下评论