通过指令的方式来实现元素加载过渡效果

页面上如何使用 给需要过渡的元素添加 v-slide-in 指令

<template>
    <div class="continer">
        <div v-slide-in class="item">1</div>
        <div v-slide-in class="item">2</div>
        <div v-slide-in class="item">3</div>
        ...
    </div>
</template>

效果:当元素出现在试图后,会缓动到目标位置

 

指令代码:

const DISTANCE = 100;
const DURATION = 500;

const animationMap = new WeakMap()
const ob = new IntersectionObserver((entires) => {
    for(const entry of entires){
        if(entry.isIntersecting){
            animationMap.get(entry.target).play()
            ob.unobserve(entry.target)
        }
    }

})

function isBelowViewPort (el) {
    const rect = el.getBoundingClientRect();
    return rect.top > window.innerHeight;
}
export default {
    
    mounted(el){
        setTimeout(() => {
            if(!isBelowViewPort(el)){   //只有当元素在视口top值下面的时候才会触发animate
                return;
            }
            const animation = el.animate(
                [
                    {
                        transform: `translateY(${DISTANCE}px)`,
                        opacity:0.5
                    },
                    {
                        transform: `translateY(0px)`,
                        opacity:1,
                    }
                ], 
                {
                    duration: DURATION,
                    easing: 'ease'
                }
            )
            animation.pause()
            animationMap.set(el, animation)
            ob.observe(el)
        },0)

    },
    unmounted(el){
       ob.unobserve(el)
    }
}

 

posted @ 2023-06-09 17:13  10后程序员劝退师  阅读(32)  评论(0编辑  收藏  举报