首页 > 解决方案 > 为什么anime.js不适用于跨度元素

问题描述

我正在尝试使用anime.js为标题中的每个字母设置动画,方法是将标题的每个字母放入一个跨度中。但由于某种原因,我无法为跨度设置动画。为什么会发生这种情况,我该如何解决?

索引.html

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
    <title>Header anime animation</title>
    <link href="style.css" rel="stylesheet" type="text/css" />
</head>
<body>
    <div id="wrapper">
        <header>
            <h1 id="mainheader">
                <span class="header-text" id="f">f</span><span class="header-text" id="o-1">o</span><span class="header-text" id="o-2">o</span>
            </h1>
        </header>
    </div>

    <script src="https://unpkg.com/animejs@3.2.1/lib/anime.min.js"></script>
    <script src="script.js"></script>
</body>
</html>

样式.css

div#wrapper {
    height: 90vh;
    width: 100%;
    margin: 0;
    padding: 0;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
}

h1#mainheader {
    position: relative;
    top: 50px;
}

脚本.js

anime({
    targets: '.header-text',
    translateY: -50,
    duration: 1000,
    delay: anime.stagger(100),
    easing: "easeInOutExpo",
    autoplay: true
})

标签: anime.js

解决方案


这是因为 span 元素是内联元素,但anime.js 仅适用于display: blockor display: inline-block。所以在 style.css 中,只需添加

span.header-text {
    display: inline-block
}

推荐阅读