深色和浅色模式:如何切换清单和图标?

Bil*_*ill 10 javascript favicon macos-darkmode

清单和图标取决于浅色/深色模式,当用户更改操作系统中的模式时,有什么方法可以更改它们吗?

我已经触发了事件侦听器

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

但清单是从反应公共文件夹加载的..

<!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>
Run Code Online (Sandbox Code Playgroud)

不确定如何处理也在公共文件夹根目录中的图标。此外,主题颜色的元标记也需要更改。

Bil*_*ill 9

使用@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" />
Run Code Online (Sandbox Code Playgroud)

然后在头部我添加了......

    <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>

Run Code Online (Sandbox Code Playgroud)