答案:通过CSS媒体查询检测系统偏好,结合JavaScript实现手动切换与本地存储。使用prefers-color-scheme区分亮暗色主题,data-theme属性控制样式,localStorage保存用户选择,支持自动、亮色、暗色三种模式,并通过过渡动画和预设主题避免闪屏,确保体验流畅。

实现暗黑模式切换和根据用户偏好自动适配,主要依靠 HTML、CSS 和 JavaScript 的结合使用,配合 媒体查询(media query) 检测用户的系统偏好。下面介绍完整实现方法。
示例代码:
<pre class="brush:php;toolbar:false;">
@media (prefers-color-scheme: light) {
:root {
--bg-color: #ffffff;
--text-color: #000000;
}
}
@media (prefers-color-scheme: dark) {
:root {
--bg-color: #1a1a1a;
--text-color: #f0f0f0;
}
}
HTML 结构:
<pre class="brush:php;toolbar:false;"> <button id="theme-toggle">切换暗黑模式</button>
CSS 设置数据属性控制主题:
立即学习“前端免费学习笔记(深入)”;
<pre class="brush:php;toolbar:false;">
[data-theme="light"] {
--bg-color: #ffffff;
--text-color: #000000;
}
[data-theme="dark"] {
--bg-color: #1a1a1a;
--text-color: #f0f0f0;
}
body {
background-color: var(--bg-color);
color: var(--text-color);
transition: background-color 0.3s ease;
}
JavaScript 实现切换逻辑:
<pre class="brush:php;toolbar:false;">
const toggleButton = document.getElementById('theme-toggle');
const currentTheme = localStorage.getItem('theme') || 'auto'; // 默认自动
// 应用主题
function applyTheme(theme) {
if (theme === 'auto') {
document.body.removeAttribute('data-theme');
// 使用媒体查询判断
const systemPrefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches;
document.body.setAttribute('data-theme', systemPrefersDark ? 'dark' : 'light');
} else {
document.body.setAttribute('data-theme', theme);
}
}
// 切换按钮点击事件
toggleButton.addEventListener('click', () => {
const current = localStorage.getItem('theme') || 'auto';
let nextTheme;
if (current === 'light') {
nextTheme = 'dark';
} else if (current === 'dark') {
nextTheme = 'auto';
} else {
nextTheme = 'light';
}
localStorage.setItem('theme', nextTheme);
applyTheme(nextTheme);
});
// 页面加载时初始化
applyTheme(currentTheme);
// 监听系统主题变化(当设置为 auto 时生效)
window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', e => {
const current = localStorage.getItem('theme');
if (current === 'auto') {
applyTheme('auto');
}
});
prefers-color-scheme
以上就是html函数如何实现暗黑模式切换 html函数偏好设置的媒体查询的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号