美文网首页
CSS3动画

CSS3动画

作者: hellomyshadow | 来源:发表于2022-01-15 13:14 被阅读0次

    transition

    transform

    transform 不会使DOM脱离文档流,当通过 translateX 等属性值移动了元素后,它仍然占据原来的位置。
    好处是,transform 制作的动画会直接进入合成阶段,避开重排重绘,可以通过 Performance 录制面板来查看 transform 动画的效率。

    animation

    MDN animation
    深入浅出CSS动画

    animate

    MDN animate()

    var animation = element.animate(keyframes, options); 
    

    animate() 方法是一个创建新Animation的便捷方法,将它应用于元素,然后运行动画。它将返回一个新建的 Animation 对象实例。

    dom.animate([
        // keyframe
        { transform: 'translateX(0)' },
        { transform: 'translateX(-300px)' },
    ], {
        duration: 1000 * 20,  // 20s
        delay: 1000 * 0.5,    // 500 ms
        easing: 'linear',
        iterations: Infinity,
    })
    

    无限轮播

    轮播原理.png
    .swiper-box {
       animation: move-roll 20s linear .5s infinite;
    }
    
    @keyframes move-roll {
      0% {
        transform: translateX(0);
      }
      100% {
        transform: translateX(-300px);
      }
    }
    

    监听 CSS animation 动画的事件:

    // 只对 CSS animation 动画有效
    dom.addEventListener("animationend", (e) => {
        // 一次动画结束
    });
    dom.addEventListener("animationstart", (e) => {
        // 一次动画开始
    });
    dom.addEventListener("animationiteration", (e) => {
        // 动画重复执行
    });
    

    这些监听事件对 animate() 是无效的。

    公告轮播

    页面顶部经常会见到水平无限轮播的公告。
    由于轮播的内容是动态的,可能很多,也可能很少,如果公告内容的宽度没有超过最大宽度限制,那么就不应该轮播,如果超过了,则发起轮播。
    假设我们永远只有一条最新的公告

    <div class="swiper-box" ref={swiperRef}>
        <p>这是轮播内容</p>
        {    // 只有在需要轮播时,才能追加这个影子
              isRoll ? (<p style="padding-left: 60px">这是轮播内容</p>) : null
        }
    <div>
    

    原理:当一次动画执行结束时,影子内容的头部刚好对准轮播内容的初始位置,那么下次动画开始时,轮播内容将重新回到初始位置,由于影子内容与轮播内容相同,那么就给人造成一种无限轮播的错觉。

    逻辑实现:父元素设置了 overflow: hidden,又想要获取父元素、子元素的真实宽度,那么可以通过 scrollWidth 获取。

    useEffect(() => {
        if(!text) return;
        const { clientWidth, firstChild } = swiperRef.current;
        // 内容长度
        const txtWidth = (firstChild as HTMLParagraphElement).scrollWidth;
        // 是否启用轮播:文本宽度大于 父元素上设置的宽度了,则开启轮播
        setRoll(txtWidth > clientWidth);
    }, [text])
    
    useEffect(() => {
        if(!isRoll) return
        const { clientWidth, lastChild } = swiperRef.current
        // 内容 + padding 长度
        const offsetX = (lastChild as HTMLParagraphElement).scrollWidth
        // 计算一次动画的时间,这里的动画时间基数是 30s
        // 基数计算方式:当文本长度刚好 = 父元素宽度时,不断调整动画时间,速度合适的时间就是基数时间
        const duration = Math.round(offsetX / clientWidth * 30 * 100) / 100
        // 开始轮播
        const animation = swiperRef.current.animate([
          // keyframe
          { transform: 'translateX(0)' },
          { transform: `translateX(-${offsetX}px)` },
        ], {
          duration: 1000 * duration,
          delay: 1000 * 0.5,
          easing: 'linear',
          iterations: Infinity,
        })
        return () => {
          animation.cancel()
        }
    }, [isRoll])
    

    兼容性:如果不支持 animate(),那么我们可以动态创建 <style> + @keyframes,插入 <head>, 但也要记得移除。

    // 准备样式文本
    const keyframes = `
        @keyframes move{
            from{
                transform: translateX(0);
            }
            to{
                transform: translateX(300px);
            }
        }
    `
    // 创建 <style>
    const style = document.createElement('style')
    style.id = 'swiperKeyframes'  // 加上 id,方便移除
    style.type = 'text/css'
    // 插入样式文本
    const textNode = document.createTextNode(keyframes);
    style.appendChild(textNode);
    // 把 <style> 插入 <head>
    const head = document.head || document.getElementsByTagName('head')[0]
    head.appendChild(style)
    
    // 如果css是external的话会报错:
    //  Uncaught DOMException: Failed to read the 'cssRules' property from 'CSSStyleSheet': Cannot access rules
    // styleSheet.insertRule(keyframes, styleSheet.cssRules.length);
    
    
    // 移除
    const style = document.querySelectorAll("#swiperKeyframes")
    style.forEach(keyframe => document.head.removeChild(keyframe))
    

    相关文章

      网友评论

          本文标题:CSS3动画

          本文链接:https://www.haomeiwen.com/subject/ewsbihtx.html