addEffect()
当按 行
进行分割时,保留动画和回调在分割间的状态,并允许使用 split.revert()
一次性还原所有分割动画。
const split = text.split({
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();
当满足以下条件时,效果的动画或回调会自动刷新:
- 调用
text.split()
且document.fonts.ready
Promise
解析时 (如果尚未解析,则立即触发)。 - 按
行
分割且目标元素的宽度发生变化时,无论行结构是否实际改变。
接受
一个 函数
,其第一个参数是 SplitText
自身,可返回一个动画、时间轴、计时器或一个可选的清理函数,该清理函数会在每次后续的行计算之前被调用。
addEffect() 代码示例
import { animate, utils, stagger, text } from 'animejs';
const colors = [];
text.split('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>