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'
相关推荐
葡萄城技术团队15 小时前
1000 人协同压测的环境瓶颈排查:CPU 争用与 Wi\-Fi
前端
Java后端的Ai之路15 小时前
CAS并发控制-从CPU指令到企业级乐观锁
vue.js·人工智能·python·cas·乐观锁
excel16 小时前
Marked 与 Markdown 有什么区别?该怎么选?
前端
Da Da 泓17 小时前
五子棋 Web 端测试用例报告
前端·网络·websocket·网络协议·测试用例·项目
zxcvb15317 小时前
远程查看本地文档:一条轻量 Web 文件服务的工程化链路
前端·远程查看文档
niucloud-admin18 小时前
NIUCLOUD PHP SAAS上门家政使用文档:城市管理
java·前端·php
程序员大阳18 小时前
副队长JavaScript教程(50)-DOM:网页开发的起点
javascript·dom·es·节点·概念·document·关系
北岛贰18 小时前
啵啵音乐迎来全新升级!
前端
hkNaruto20 小时前
【AI】基于大模型的AI游戏地图生成、控制方案:AI Native Game Harness 迁移操作手册
前端·人工智能·游戏
IT_陈寒20 小时前
Java序列化踩坑记:对象循环引用让我加班两小时
前端·人工智能·后端