v-slide-in元素首次进入视图内动画效果

元素首次进入视图内显示从下到上滑入的动画效果。

import Vue from "vue";
//动画距离

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);
    }
  }
});

/**
 * 判断给定的元素是否在视图范围之外
 * @param {HTMLElement} el - 要判断的元素
 * @returns {boolean} - 如果元素在视图范围之外则返回true,否则返回false
 */
function isBelowViewPort(el) {
  const rect = el.getBoundingClientRect();
  return rect.top > window.innerHeight;
}
Vue.directive("slideIn", {
  bind(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);
    }, 100);
  },
  unbind(el) {
    ob.unobserve(el);
  },
});

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值