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

10

清单文件和网站图标取决于浅色/深色模式,是否有办法在用户更改操作系统的模式时进行更改?

我已经使事件监听器触发。

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

但是清单文件是从React的public文件夹中加载的。

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

不确定如何处理位于公共文件夹根目录中的网站图标。另外,theme-color 的元标记也需要更改。


https://www.npmjs.com/package/react-helmet - Roberto Zvjerković
2个回答

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

然后在头部部分,我添加了...
    <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>


为什么需要更新manifest.json文件? - Shadoath

-1

你可以使用 JavaScript 动态更改

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

在 onchange 函数内执行此操作


我没有给你的回答点踩,但是你应该提供一份解释你代码的说明,它如何帮助和为什么这样做。你基本上只是说“这样做”,这不是一个好的回答。看看Bill自己发布的答案 - 这就是你应该回答问题的方式。 - Reinstate Monica Cellio
1
我只能提供一个编程的想法,但我没有办法为你编写代码。人们需要的只是一个想法。如果它奏效了,你可以给我的答案点赞并接受它。 - kishore kingmaker
我做了,它将您从-1提升到了0。 - Bill

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接