addEffect()

在按 lines拆分时,保留拆分之间的动画和回调状态,并允许使用 split.revert()一次性恢复所有拆分动画。

const split = splitText({
  lines: true,
  chars: true,
});

// Doesn't work when splitting by lines because the split can be delayed by the fonts loading
animate([split.lines, split.words, split.chars], {
  opacity: { from: 0 },
});

// Works! addEffect() will be safely executed after each split
// making sure the split elements are always up to date
split.addEffect(({ lines, words, chars }) => animate([lines, words, chars], {
  opacity: { from: 0 },
}));

// Reverts both the text split and the effect animation
split.revert();

当发生以下情况时,效果的动画或回调会自动刷新:

  • splitText() is called and the document.fonts.ready Promise resolves (if it wasn't already resolved, otherwise triggers immediately).
  • Splitting by lines and the target element's width has changed, regardless of whether the line structure actually changes

接受

一个 Function,其第一个参数是 SplitText 本身,可以返回 Animation、Timeline、Timer 或一个可选的清理函数,该函数在每次后续行计算之前调用。

addEffect() 代码示例

import { animate, utils, stagger, splitText } from 'animejs';

const colors = [];

splitText('p', {
  lines: true,
})
/* Registering an animation to the split */
.addEffect(({ lines }) => animate(lines, {
  y: ['50%', '-50%'],
  loop: true,
  alternate: true,
  delay: stagger(400),
  ease: 'inOutQuad',
}))
/* Registering a callback to the split */
.addEffect(split => {
  split.words.forEach(($el, i) => {
    const color = colors[i];
    if (color) utils.set($el, { color });
    $el.addEventListener('pointerenter', () => {
      animate($el, {
        color: utils.randomPick(['#FF4B4B', '#FFCC2A', '#B7FF54', '#57F695']),
        duration: 250,
      })
    });
  });
  return () => {
    /* Called between each split */
    split.words.forEach((w, i) => colors[i] = utils.get(w, 'color'));
  }
});
<div class="iframe-content resizable">
  <div class="medium centered row">
    <p class="text-l">Hover the words to animate their color, then resize the text.</p>
  </div>
</div>