animate.css:css 动画库 https://animate.style/

    引入样式文件

    1. import 'animate.css';

    添加属性

    1. const animateProps = {
    2. "animate-name": "fadeInUp", // 这个名字不重要。当有多种动画时会排上用场
    3. "animate-duration": '0.5', // 动画持续时长
    4. }
    5. 如果是循环节点,可借助函数动态添加动态持续时长
    6. const getDuration = (index: number) => {
    7. return 1 + parseFloat('0.' + ((index + 1) * 2 - 1))
    8. }
    1. <div
    2. className={styles.title}
    3. {...animateProps}>
    4. {formatMessage({ id: "Index_REALTIMEPOOLSTATS" })}
    5. </div>

    判断html是否进入视野

    1. // 判断元素是否在可视范围内
    2. export function elementInViewport(element) {
    3. const rect = element.getBoundingClientRect();
    4. return (
    5. (rect.top >= 0 || rect.bottom >= 0) &&
    6. (rect.left >= 0 || rect.right >= 0) &&
    7. rect.top <= (window.innerHeight || document.documentElement.clientHeight)
    8. );
    9. }

    动态添加样式
    1.react

    1. useEffect(() => {
    2. const handleAnimateListen = () => {
    3. const animateEls = document.querySelectorAll('[animate-name]') as NodeListOf<HTMLElement>;
    4. for (const el of animateEls) {
    5. if (elementIntoViewport(el)) {
    6. let animateDelay = el.getAttribute('animate-duration')
    7. console.log('animateDelay: ', animateDelay);
    8. if (!el.classList.contains('animate__animated')) {
    9. el.classList.add('animate__animated', 'animate__fadeInUp'); // 添加动画类名
    10. el.style.setProperty('--animate-duration', `${animateDelay}s`); // 动画时长
    11. }
    12. }
    13. }
    14. }
    15. const animateEls = document.querySelectorAll('[animate-name]')
    16. if (animateEls && animateEls.length > 0) {
    17. handleAnimateListen();
    18. document.addEventListener("scroll", handleAnimateListen, false);
    19. }
    20. return () => document.removeEventListener("scroll", handleAnimateListen, false);
    21. }, [])

    2.vue

    1. const handleAnimateListen = () => {
    2. const animateEls = document.querySelectorAll('[data-animate]')
    3. for (const el of animateEls) {
    4. if (elementInViewport(el)) {
    5. let animateDelay = el.getAttribute('data-delay')
    6. if (!el.classList.contains('animate__animated')) {
    7. el.classList.add('animate__animated', 'animate__fadeInUp')
    8. el.style.setProperty('--animate-duration', `${animateDelay}s`);
    9. }
    10. }
    11. }
    12. }
    13. onMounted(() => {
    14. setTimeout(() => {
    15. const animateEls = document.querySelectorAll('[data-animate]')
    16. if (animateEls && animateEls.length > 0) {
    17. handleAnimateListen();
    18. document.addEventListener("scroll", handleAnimateListen, false);
    19. }
    20. }, 0)
    21. });
    22. onUnmounted(() => {
    23. document.removeEventListener('scroll', handleAnimateListen, false)
    24. });