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'
相关推荐
加班是不可能的,除非双倍日工资4 小时前
css预编译器实现星空背景图
前端·css·vue3
wyiyiyi4 小时前
【Web后端】Django、flask及其场景——以构建系统原型为例
前端·数据库·后端·python·django·flask
gnip5 小时前
vite和webpack打包结构控制
前端·javascript
excel5 小时前
在二维 Canvas 中模拟三角形绕 X、Y 轴旋转
前端
阿华的代码王国5 小时前
【Android】RecyclerView复用CheckBox的异常状态
android·xml·java·前端·后端
一条上岸小咸鱼5 小时前
Kotlin 基本数据类型(三):Booleans、Characters
android·前端·kotlin
Jimmy5 小时前
AI 代理是什么,其有助于我们实现更智能编程
前端·后端·ai编程
草梅友仁5 小时前
草梅 Auth 1.4.0 发布与 ESLint v9 更新 | 2025 年第 33 周草梅周报
vue.js·github·nuxt.js
ZXT6 小时前
promise & async await总结
前端
Jerry说前后端6 小时前
RecyclerView 性能优化:从原理到实践的深度优化方案
android·前端·性能优化