animate.css
:css 动画库 https://animate.style/
引入样式文件
import 'animate.css';
添加属性
const animateProps = {
"animate-name": "fadeInUp", // 这个名字不重要。当有多种动画时会排上用场
"animate-duration": '0.5', // 动画持续时长
}
如果是循环节点,可借助函数动态添加动态持续时长
const getDuration = (index: number) => {
return 1 + parseFloat('0.' + ((index + 1) * 2 - 1))
}
<div
className={styles.title}
{...animateProps}>
{formatMessage({ id: "Index_REALTIMEPOOLSTATS" })}
</div>
判断html是否进入视野
// 判断元素是否在可视范围内
export function elementInViewport(element) {
const rect = element.getBoundingClientRect();
return (
(rect.top >= 0 || rect.bottom >= 0) &&
(rect.left >= 0 || rect.right >= 0) &&
rect.top <= (window.innerHeight || document.documentElement.clientHeight)
);
}
动态添加样式
1.react
useEffect(() => {
const handleAnimateListen = () => {
const animateEls = document.querySelectorAll('[animate-name]') as NodeListOf<HTMLElement>;
for (const el of animateEls) {
if (elementIntoViewport(el)) {
let animateDelay = el.getAttribute('animate-duration')
console.log('animateDelay: ', animateDelay);
if (!el.classList.contains('animate__animated')) {
el.classList.add('animate__animated', 'animate__fadeInUp'); // 添加动画类名
el.style.setProperty('--animate-duration', `${animateDelay}s`); // 动画时长
}
}
}
}
const animateEls = document.querySelectorAll('[animate-name]')
if (animateEls && animateEls.length > 0) {
handleAnimateListen();
document.addEventListener("scroll", handleAnimateListen, false);
}
return () => document.removeEventListener("scroll", handleAnimateListen, false);
}, [])
2.vue
const handleAnimateListen = () => {
const animateEls = document.querySelectorAll('[data-animate]')
for (const el of animateEls) {
if (elementInViewport(el)) {
let animateDelay = el.getAttribute('data-delay')
if (!el.classList.contains('animate__animated')) {
el.classList.add('animate__animated', 'animate__fadeInUp')
el.style.setProperty('--animate-duration', `${animateDelay}s`);
}
}
}
}
onMounted(() => {
setTimeout(() => {
const animateEls = document.querySelectorAll('[data-animate]')
if (animateEls && animateEls.length > 0) {
handleAnimateListen();
document.addEventListener("scroll", handleAnimateListen, false);
}
}, 0)
});
onUnmounted(() => {
document.removeEventListener('scroll', handleAnimateListen, false)
});