简体   繁体   English

明暗模式:如何切换清单和网站图标?

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

The manifest and the favicon are dependent on the light/darkmode is there any way of changing them as the user changes the mode in the operating system? manifest 和 favicon 依赖于 light/darkmode 是否有任何方法可以在用户更改操作系统模式时更改它们?

Ive got the event listener firing我已经触发了事件侦听器

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

but the manifest is loaded from the react public folder..但清单是从反应公共文件夹加载的。

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

Not sure how to handle the favicon that is also in the root of the public folder.不确定如何处理也在公用文件夹根目录中的图标。 Also the meta tag for theme-color would need to change.主题颜色的元标记也需要更改。

Using the suggestion from @kishore I've managed to get the favicon working, I'm sure someone better can tighten up my code but it works, in the html I added an id...使用来自@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" />

then in the head section I added...然后在头部部分我添加了...

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

you can change dynamically using js您可以使用 js 动态更改

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

do this inside onchange function在 onchange 函数中执行此操作

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM