清单和收藏夹图标取决于明/暗模式,当用户在操作系统中更改模式时,是否有任何更改方式?
我已经触发了事件监听器
window.matchMedia('(prefers-color-scheme: dark)').addEventListener( "change", (e) => {
if (e.matches) console.log('your in dark mode);
});
但是清单是从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>
不确定如何处理公用文件夹根目录中的收藏夹图标。另外,主题颜色的meta标签也需要更改。
答案 0 :(得分:1)
使用@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 darkMode = window.matchMedia('(prefers-color-scheme: dark)').matches || false;
const favicon = document.getElementById('favicon');
const manifest = document.getElementById('manifest');
function switchIcon(darkMode) {
if (darkMode) {
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(darkMode);
</script>
答案 1 :(得分:0)
您可以使用js动态更改
document.getElementById('favicon_id').href = 'required_link'
在onchange函数中执行此操作