javascript - 暗光模式 : How to switch manifest and favicon?

标签 javascript favicon macos-darkmode

manifest 和 favicon 依赖于 light/darkmode 是否有任何方法可以在用户更改操作系统模式时更改它们?

我触发了事件监听器

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

但 list 是从 React 公用文件夹加载的..

<!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 的建议,我已经设法使网站图标正常工作,我相信有人可以更好地收紧我的代码,但它确实有效,在 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>

关于javascript - 暗光模式 : How to switch manifest and favicon?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57754710/

相关文章:

macos - NSColor systemColor 在暗/亮模式切换时不改变

javascript - 根据数字设置位数(JS)

javascript - 没有 Node 的 Require.js 优化?

javascript - jquery函数放在哪里

html - 直接 IP 和 DNS 地址之间的 CSS 和网站图标不同

web - 在 Google 阅读器中显示原子提要的图标

html - 网站图标未出现在 iPhone 6(主屏幕)上

javascript - 如何使 div 可点击以打开链接?

css - 如何在 MacOS Mojave 中使用 CSS 暗模式?