VueUse、View Transitions API实现暗黑模式主题动画切换效果

作者GitHub:github.com/gitboyzcf 有兴趣可关注!!

前言

View Transitions API

View Transitions API 是原生JavaScript提供一种能让Dom更加丝滑的API

示例 👇

兼容版本

VueUse

Vue的工具函数合集 vueuse.org/

正题

效果

安装

bash 复制代码
npm install @vueuse/core
or
pnpm install @vueuse/core
or
yarn add @vueuse/core

代码

以下代码放入自己项目对应文件中即可

css 复制代码
::view-transition-old(root),
::view-transition-new(root) {
  animation: none;
  mix-blend-mode: normal;
}

/* 进入dark模式和退出dark模式时,两个图像的位置顺序正好相反 */

::view-transition-old(root) {
  z-index: 1;
}

::view-transition-new(root) {
  z-index: 2147483646;
}

/* 根据自己选择器修改 */
[data-bs-theme="dark"]::view-transition-old(root) {
  z-index: 2147483646;
}
[data-bs-theme="dark"]::view-transition-new(root) {
  z-index: 1;
}
javascript 复制代码
import { useDark, useToggle } from '@vueuse/core'

const isDark = useDark({
  selector: 'html',
  attribute: 'data-bs-theme',
  valueDark: 'dark',
  valueLight: 'light'
})

const toggleDark = useToggle(isDark);

const toggleTheme = (event) => {
  const x = event.clientX;
  const y = event.clientY;
  const endRadius = Math.hypot(
    Math.max(x, innerWidth - x),
    Math.max(y, innerHeight - y)
  );

  // 兼容性处理
  if (!document.startViewTransition) {
    toggleDark();
    return;
  }
  const transition = document.startViewTransition(async () => {
    toggleDark();
  });

  transition.ready.then(() => {
    const clipPath = [
      `circle(0px at ${x}px ${y}px)`,
      `circle(${endRadius}px at ${x}px ${y}px)`,
    ];
    console.log(isDark.value);
    document.documentElement.animate(
      {
        clipPath: isDark.value ? [...clipPath].reverse() : clipPath,
      },
      {
        duration: 400,
        easing: "ease-in",
        pseudoElement: isDark.value
          ? "::view-transition-old(root)"
          : "::view-transition-new(root)",
      }
    );
  });
};

示例

github.com/gitboyzcf/v...

到这里就结束了,后续还会更新 前端 系列相关,还请持续关注! 感谢阅读,若有错误可以在下方评论区留言哦!!!

推荐文章👇

太丝滑了!了解一下原生的视图转换动画 View Transitions

相关推荐
天蓝色的鱼鱼12 分钟前
别再瞎转Base64了!一文打通前端二进制任督二脉
前端
哟哟耶耶15 分钟前
Plugin-安装Vue.js devtools6.6.3扩展(组件层级可视化)
前端·javascript·vue.js
梦65027 分钟前
【前端实战】图片元素精准定位:无论缩放,元素始终钉在指定位置
前端·html·css3
烟袅1 小时前
一文搞懂 useRef:它到底在“存”什么?
前端·react.js
Knight_AL1 小时前
Vue + Spring Boot 项目统一添加 `/wvp` 访问前缀实践
前端·vue.js·spring boot
前端er小芳1 小时前
前端虚拟列表滚动功能实现与核心知识点详解
前端
wuhen_n1 小时前
Promise状态机与状态流转
前端
3秒一个大1 小时前
React 中的 useMemo 与 useCallback:性能优化的利器
前端·react.js
cj81401 小时前
Node.js基本概念理解
前端·node.js
ohyeah1 小时前
React 缓存三剑客:useMemo、useCallback 与 memo 的正确打开方式
前端·react.js