Vue 元素动画缓入效果

效果展示
vue文件的指令使用
css 复制代码
<style lang="scss">
.container {
  width: 88%;
  margin: 1rem auto;
  .item {
    background:url('../assets/boxImg.jpg') no-repeat;
    background-size: 100% 100%;
    width: 100%;
    height: 300px;
    margin-bottom: 20px;
    display: flex;
    align-items: center;
    justify-content: center;
    color: #fff;
    font-size: 3rem; 
  }
}
</style>
css 复制代码
  <div class="container">
    <div class="item" v-domSlown v-for="(item, index) in 10" :key="index" > 
    </div>
  </div>
指令文件
javascript 复制代码
//domSlowness.js

import Vue from 'vue';
 
// 判断元素是不是在视口之下
function isBelowViewport(el) {
    const rect = el.getBoundingClientRect();
    return rect.top > window.innerHeight;
}
const DISTANCE = 150;
const DURATION = 1000;
const animationMap = new WeakMap();

const ob = new IntersectionObserver(entries => {
    for (const entry of entries) {
        if (entry.isIntersecting) {    // 判断元素是否与视口交叉
            const animation = animationMap.get(entry.target);
            animation.play();
            ob.unobserve(entry.target);
        }
    }
})
Vue.directive('domSlown',{ 
    inserted(el,binding){
       
        if (!isBelowViewport(el)) {
            return;
        }
        const animation = el.animate([
            {
                transform: `translateY(${DISTANCE}px)`,
                opacity: 0.5
            },
            {
                transform: 'translateY(0)',
                opacity: 1
            },
        ],
            {
                duration: DURATION,
                easing: 'ease'
            })
        animation.pause();
        animationMap.set(el, animation);
        ob.observe(el);
    },
    unbind(el) {
        ob.unobserve(el);
    }
})
 
 
主文件入口引用指令文件
javascript 复制代码
//main.js
import '@/assets/domSlowness.js'
相关推荐
红色的小鳄鱼3 分钟前
Vue 教程 自定义指令 + 生命周期全解析
开发语言·前端·javascript·vue.js·前端框架·html
coloma20124 分钟前
COCOS代码动态增加刚体和碰撞体的方法
前端·uv
●VON6 分钟前
React Native for OpenHarmony:解构 TouchableOpacity 的触摸反馈与事件流控制
javascript·学习·react native·react.js·性能优化·openharmony
有诺千金8 分钟前
VUE3入门很简单(5)---组件通信(自定义事件)
javascript·vue.js·ecmascript
想逃离铁厂的老铁8 分钟前
Day60 >> 94、城市间货物运输1️⃣ + 95、城市间货物运输 2️⃣ + 96、城市间货物运输 3️⃣
java·服务器·前端
GISer_Jing1 小时前
WebGL跨端兼容实战:移动端适配全攻略
前端·aigc·webgl
daols881 小时前
vue 甘特图 vxe-gantt 自定义任务条插槽模板的用法
vue.js·vxe-gantt
迦南giser1 小时前
前端性能——传输优化
前端
小白_ysf1 小时前
Vue 中常见的加密方法(对称、非对称、杂凑算法)
前端·vue.js·算法
2501_944448002 小时前
Flutter for OpenHarmony衣橱管家App实战:支持我们功能实现
android·javascript·flutter