之前的文章中提到了黑暗模式的媒体查询新特性 #107 今天联想到了 GitHub 的自动 favicon 的实现,话不多说,先上代码: ```html <svg width="100" height="100" xmlns="http://www.w3.org/2000/svg"> <style> circle { fill: yellow; stroke: black; stroke-width: 3px; } @media (prefers-color-scheme: dark) { circle { fill: black; stroke: yellow; } } </style> <circle cx="50" cy="50" r="47"/> </svg> ``` 这是一种实现方式,不用 js,直接使用媒体查询的方式改变颜色。不过审查源码后发现 GitHub 并没有直接采用这种方式。 GitHub 采用的另外一种是间接使用媒体查询,使用 js 设置事件监听,动态改变 link 标签里的 favicon 路径 ```html <link rel="icon" href="https://github.githubassets.com/favicons/favicon-dark.svg"> ``` 监听: ```js matcher = window.matchMedia('(prefers-color-scheme: dark)'); ``` 图片和例子将在之后补充~回家~ --------------------- 相关链接: - [stackoverflow](https://stackoverflow.com/questions/55170708/detect-if-the-browser-is-using-dark-mode-and-use-a-different-favicon) - [css-tricks](https://css-tricks.com/dark-mode-favicons/)
Activity