你瞅啥呢

2024-07-24 记录一则网页换肤效果

效果:点击切换按钮,背景色由白色变成黑色,从指定的地方开始过渡

 点击按钮:

<div ref="themeBtn" @click="changeTheme">点击切换</div>

切换逻辑:

复制代码
// 主题切换按钮
const themeBtn = ref(null);

/* 改变颜色 */
const changeTheme = () => {
    // 创建一个过渡对象
    const transition = document.startViewTransition(() => {
        document.documentElement.classList.toggle('dark')
    })

    const width = themeBtn.value.getBoundingClientRect().width // 按钮的宽度
    const height = themeBtn.value.getBoundingClientRect().height // 按钮的高度
    const x = themeBtn.value.getBoundingClientRect().x + width / 2 // 按钮的中心x坐标
    const y = themeBtn.value.getBoundingClientRect().y + height / 2 // 按钮的中心y坐标

    // 计算展开圆的半径
    const tragetRadius = Math.hypot(
        Math.max(x, window.innerWidth - x),
        Math.max(y, window.innerHeight - y)
    )

    // 设置过渡的动画效果
    transition.ready.then(() => {
        document.documentElement.animate({
            clipPath: [`circle(0% at ${x}px ${y}px)`, `circle(${tragetRadius}px at ${x}px ${y}px)`]
        }, {
            duration: 1000,
            // pseudoElement 
            // 设置过渡效果的伪元素,这里设置为根元素的伪元素
            // 这样过渡效果就会作用在根元素上
            pseudoElement: '::view-transition-new(root)',
        })
    })
}
复制代码

样式:

复制代码
:root {
    --background-color: #fff;
    --color: #282c34;
    background-color: var(--background-color);
    color: var(--color);
  }
  
  :root.dark {
    --background-color: #282c34;
    --color: #fff;
  }
  
  /* 隐藏默认的过渡效果 */
  ::view-transition-new(root),
  ::view-transition-old(root) {
    animation: none;
  }
复制代码

注意:本文参照https://juejin.cn/post/7363836438935552035来写的,可以看下原文,支持一下原作者。

 

posted @   叶乘风  阅读(32)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
历史上的今天:
2022-07-24 2022-07-04 At least one Certificate issuer field is required to be non-empty
2022-07-24 2022-07-24 java.io.IOException: Keystore was tampered with, or password was incorrect
2022-07-24 2022-07-04 rnapp 如何更换启用图标
点击右上角即可分享
微信分享提示