干货:
<!DOCTYPE html>
<html lang="en"><head><meta charset="UTF-8" /><meta name="viewport" content="width=device-width, initial-scale=1.0" /><style>/* 默认的CSS变量集合 */:root {--primary: #2196f3;--background: #ffffff;--text-color: #333;}/* 修改主题的类 */.dark {--primary: #1976d2;--background: #121212;--text-color: #f1f1f1;}::view-transition-old(root),::view-transition-new(root) {animation: none;}.dark::view-transition-old(root) {z-index: 9999;}body {display: flex;justify-content: space-between;align-items: start;padding: 16px;background-color: var(--background);}/* 使用默认样式 */p {color: var(--primary);}h1 {color: var(--text-color);}h1:hover {cursor: pointer;color: var(--primary);}/* 给按钮添加样式 */button {background-color: var(--primary);color: #ffffff;padding: 8px 16px;border: none;border-radius: 4px;font-size: 16px;cursor: pointer;transition: all 0.3s ease-in-out;}</style><title>Dynamic Theme Demo</title></head><body class="body"><div><h1>Hello World</h1><p>This is a demo of switching themes with CSS variables</p></div><button id="btn">切换为黑夜</button><script>btn.addEventListener("click", handleClick);function handleClick(e) {// Fallback for browsers that don't support this API:if (!document.startViewTransition) {updateTheDOMSomehow();return;}// With a View Transition:const transition = document.startViewTransition(() =>updateTheDOMSomehow());transition.ready.then(() => {const x = e.clientX;const y = e.clientY;const clipPath = [`circle(0 at ${x}px ${y}px)`,`circle(100% at ${x}px ${y}px)`,];const isDark = document.documentElement.classList.contains("dark");document.documentElement.animate({clipPath: isDark ? clipPath.reverse() : clipPath,},{duration: 500,pseudoElement: isDark? "::view-transition-old(root)": "::view-transition-new(root)",});});}function updateTheDOMSomehow() {document.documentElement.classList.toggle("dark");var button = document.querySelector("button");var theme = document.documentElement.classList.contains("dark")? "切换为白天": "切换为黑夜";button.textContent = theme;}</script></body>
</html>