」工欲善其事,必先利其器。「—孔子《論語.錄靈公》
首頁 > 程式設計 > 查看過渡主題動畫

查看過渡主題動畫

發佈於2024-11-04
瀏覽:427

View transition theme animations

使用 CSS 和視圖轉換從淺色模式轉換為深色模式時添加酷炫效果

複製自 Twitter 上的@jhey

[!筆記]
這假設您已經設定了暗光模式,並具有某種功能來更新您的主題

  1. 新增CSS
  /* Angled */
  [data-style='angled']::view-transition-old(root) {
    animation: none;
    z-index: -1;
  }

  [data-style='angled']::view-transition-new(root) {
    animation: unclip 1s;
    clip-path: polygon(-100vmax 100%, 100% 100%, 100% -100vmax);
  }

  @keyframes unclip {
    0% {
      clip-path: polygon(100% 100%, 100% 100%, 100% 100%);
    }
  }

  1. 確保在根元素上設定 data-style="angled" 屬性 在 SPA React 中我們使用 useEffect 鉤子
  useEffect(() => {
    // set the data-style attribute
    document.documentElement.dataset.style = "angled";
  }, []);

在SSR中可以直接在html標籤中設定

  1. 將主題變更函數包裝在 documnet.startViewTransition 中以啟動視圖轉換
  function transitionColors() {
    if (typeof window !== "undefined") {
      document.startViewTransition(() => {
        const newTheme = theme  === "light" ? "dark" : "light";
        document.documentElement.dataset.theme = newTheme;
        updateTheme(newTheme);
      });
    }
  }

可以透過包含對應的 css 檔案並添加正確的 data-style 屬性來新增更多過渡樣式

      

反應範例

如果你喜歡這種類型的 css 技巧,請考慮遵循 jhey

版本聲明 本文轉載於:https://dev.to/tigawanna/view-transition-theme-animations-8n1?1如有侵犯,請聯絡[email protected]刪除
最新教學 更多>

免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。

Copyright© 2022 湘ICP备2022001581号-3