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()
且document.fonts.ready
Promise
得到解决(如果它尚未解决,则立即触发)。 - 按
lines
进行拆分,并且目标元素的宽度已更改,无论行结构是否实际发生变化。
接受
一个 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>