簡體   English   中英

明暗模式:如何切換清單和網站圖標?

[英]Dark & Light Mode: How to switch manifest and favicon?

manifest 和 favicon 依賴於 light/darkmode 是否有任何方法可以在用戶更改操作系統模式時更改它們?

我已經觸發了事件偵聽器

  window.matchMedia('(prefers-color-scheme: dark)').addEventListener( "change", (e) => {
    if (e.matches) console.log('your in dark mode);
  });

但清單是從反應公共文件夾加載的。

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <meta name="theme-color" content="#000000" />
    <meta
      name="description"
      content="Web site created using create-react-app"
    />
    <link rel="apple-touch-icon" href="logo192.png" />
    <link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
    <title>My Site</title>
  </head>
  <body>
    <noscript>Please enable JavaScript to run this app.</noscript>
    <div id="root"></div>
  </body>
</html>

不確定如何處理也在公用文件夾根目錄中的圖標。 主題顏色的元標記也需要更改。

使用來自@kishore 的建議,我設法讓 favicon 工作,我相信有人可以更好地收緊我的代碼,但它有效,在 html 中我添加了一個 id ...

<link rel="shortcut icon" id='favicon' href="%PUBLIC_URL%/favicon.ico" />
<link rel="manifest" id='manifest' href="%PUBLIC_URL%/manifest.json" />

然后在頭部部分我添加了...

    <script>
      const usesDarkMode = window.matchMedia('(prefers-color-scheme: dark)').matches || false;
      const favicon = document.getElementById('favicon');
      const manifest = document.getElementById('manifest');

      function switchIcon(usesDarkMode) {
        if (usesDarkMode) { 
          favicon.href = '%PUBLIC_URL%/favicon-dark.ico';
          manifest.href='%PUBLIC_URL%/manifest-dark.json' 
        } else {
        favicon.href = '%PUBLIC_URL%/favicon-light.ico';
        manifest.href='%PUBLIC_URL%/manifest-light.json' 
        }
      }

      window.matchMedia('(prefers-color-scheme: dark)').addEventListener( "change", (e) => switchIcon(e.matches));
      switchIcon(usesDarkMode);
    </script>

您可以使用 js 動態更改

document.getElementById('favicon_id').href = 'required_link'

在 onchange 函數中執行此操作

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM