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/