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'
相关推荐
264玫瑰资源库20 分钟前
问道数码兽 怀旧剧情回合手游源码搭建教程(反查重优化版)
java·开发语言·前端·游戏
喝拿铁写前端30 分钟前
从圣经Babel到现代编译器:没开玩笑,普通程序员也能写出自己的编译器!
前端·架构·前端框架
HED37 分钟前
VUE项目发版后用户访问的仍然是旧页面?原因和解决方案都在这啦!
前端·vue.js
拉不动的猪1 小时前
前端自做埋点,我们应该要注意的几个问题
前端·javascript·面试
王景程1 小时前
如何测试短信接口
java·服务器·前端
安冬的码畜日常2 小时前
【AI 加持下的 Python 编程实战 2_10】DIY 拓展:从扫雷小游戏开发再探问题分解与 AI 代码调试能力(中)
开发语言·前端·人工智能·ai·扫雷游戏·ai辅助编程·辅助编程
烛阴2 小时前
Node.js中必备的中间件大全:提升性能、安全与开发效率的秘密武器
javascript·后端·express
小杨升级打怪中2 小时前
前端面经-JS篇(三)--事件、性能优化、防抖与节流
前端·javascript·xss
清风细雨_林木木2 小时前
Vue开发网站会有“#”原因是前端路由使用了 Hash 模式
前端·vue.js·哈希算法
鸿蒙布道师2 小时前
OpenAI为何觊觎Chrome?AI时代浏览器争夺战背后的深层逻辑
前端·人工智能·chrome·深度学习·opencv·自然语言处理·chatgpt