【问题标题】:Dark & Light Mode: How to switch manifest and favicon?明暗模式:如何切换清单和网站图标?
【发布时间】:2020-01-05 08:37:09
【问题描述】:

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>

不确定如何处理同样位于公用文件夹根目录中的网站图标。主题颜色的元标记也需要更改。

【问题讨论】:

标签: javascript favicon macos-darkmode


【解决方案1】:

使用@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>

【讨论】:

    【解决方案2】:

    你可以使用js动态改变

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

    在 onchange 函数中执行此操作

    【讨论】:

    • 我没有投反对票,但您应该解释一下您的代码、它如何提供帮助以及原因。您基本上说“这样做”,这不是一个好的答案。查看 Bill 自己发布的答案 - 这就是您应该回答问题的方式。
    • 我可以建议一个想法来编写代码。我不能给你做编码的工作。人们需要的只是想法。如果可行,您本可以投票并接受我的回答。
    • 我做到了,它把你从 -1 带到了 0
    猜你喜欢
    • 1970-01-01
    • 2020-01-17
    • 2021-05-30
    • 2020-10-01
    • 2022-01-10
    • 1970-01-01
    • 1970-01-01
    • 2020-09-06
    • 1970-01-01
    相关资源
    最近更新 更多