请问css如何实现动态更换皮肤主题?
网友回复
通过css变量来控制,再结合localstorage来实现主题刷新留存效果,代码如下:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width,initial-scale=1.0,maximum=1.0,minimum=1.0,user-scalable=0" /> <style> :root { --background-color: #fff; --text-color: #121416d8; --link-color: #543fd7; } html[data-theme='light'] { --background-color: #fff; --text-color: #121416d8; --link-color: #543fd7; } html[data-theme='dark'] { --background-color: #212a2e; --text-color: #F7F8F8; --link-color: #828fff; } body { background: var(--background-color); color: var(--text-color); } a { color: var(--link-color); } a:hover { text-decoration: underline; filter: brightness(80%); } </style> </head> <body> <div id="theme-toggle"> <a>点击切换皮肤</a> </div> <script type="text/javascript"> var toggle = document.getElementById("theme-toggle"); var storedTheme = localStorage.getItem('theme') || (window.matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light"); if (storedTheme) document.documentElement.setAttribute('data-theme', storedTheme) toggle.onclick = function() { var currentTheme = document.documentElement.getAttribute("data-theme"); var targetTheme = "light"; if (currentTheme === "light") { targetTheme = "dark"; } document.documentElement.setAttribute('data-theme', targetTheme) localStorage.setItem('theme', targetTheme); }; </script> </body> </html>