如何使用CSS变量创建暗模式主题
介绍
您可能已经注意到,在许多网站上,您现在可以在深色和浅色主题之间切换。 这通常使用 CSS 自定义属性(又名 CSS 变量 )来完成。 在本教程中,您将了解如何仅使用 CSS 和一点 JavaScript 来实现类似的功能。 要了解有关此代码如何工作的更多信息,请查看我们在 Javascript 或 HTML 上的系列内容。
第 1 步 - 创建 CSS 变量
CSS 中自定义属性的强大功能在这里真正闪耀,因为与使用 CSS 预处理器定义的变量不同,这些值是动态的; 它们的值可以根据用户输入随时更改或覆盖。 当变量的值被更改或覆盖时,所有使用该变量的元素都会自动反映该更改。
首先,您必须做一些工作并提取您想要在 CSS 自定义属性中使用的所有颜色。 假设您从以下样式开始:
样式.css
body {
background: white;
color: #555;
}
a, a:link {
color: #639A67;
}
a:hover {
color: #205D67;
}
然后,您将这样定义自定义属性:
样式.css
:root {
--bg: white;
--text-color: #555;
--link-color: #639A67;
--link-hover: #205D67;
}
有了这个,您现在可以将您的 CSS 规则更改为如下所示:
样式.css
body {
background: var(--bg);
color: var(--text-color);
}
a, a:link {
color: var(--link-color);
}
a:hover {
color: var(--link-hover);
}
应用主题涉及向 body 元素添加一个类,因此您将在该类名称下定义主题的颜色。 这里我们将调用类 funky。 只需确保为所有颜色定义覆盖颜色即可:
样式.css
.funky {
--bg: hotpink;
--text-color: white;
--link-color: #B793E6;
--link-hover: #3532A7;
}
第 2 步 — 为旧版浏览器添加回退
对 CSS 自定义属性 的支持非常好 ,但您很可能希望为使用旧浏览器的用户提供回退。
假设我们有一个元素应该有一个线性渐变背景,颜色定义为自定义属性。 你先提供硬编码的颜色,旧的浏览器会忽略他们不理解的版本:
样式.css
background: linear-gradient(to right, #FFFB85, #5A3662); /* our fallback */ background: linear-gradient(to right, var(--top-grad1), var(--top-grad2));
第 3 步 - 切换我们的主题
我们只需要非常少量的 JavaScript 就可以在一个元素上添加一个事件侦听器,该元素充当两个主题之间的切换按钮。
这里的切换按钮有 toggle-theme 类,我们使用 document.querySelector 来获取对该元素的引用:
应用程序.js
let toggle = document.querySelector('.toggle-theme');
toggle.addEventListener('click', function(e) {
e.preventDefault();
if (document.body.classList.contains('funky')) {
// Turning the theme off:
document.body.classList.remove('funky');
// Reverse logic on the button text, so that users can turn
// the theme back on:
toggle.innerText = 'Turn theme on';
} else {
document.body.classList.add('funky');
toggle.innerText = 'Turn theme off';
}
});
这可以在两个主题之间切换。 我们可以做得更好,同时向 localStorage 添加/删除项目,以便在页面加载时自动应用我们的主题:
应用程序.js
let toggle = document.querySelector('.toggle-theme');
// Turn the theme off if the 'funky' key exists in localStorage
if (localStorage.getItem('funky')) {
document.body.classList.add('funky');
toggle.innerText = 'Turn theme off';
}
toggle.addEventListener('click', function(e) {
e.preventDefault();
if (document.body.classList.contains('funky')) {
document.body.classList.remove('funky');
toggle.innerText = 'Turn theme on';
localStorage.removeItem('funky');
} else {
document.body.classList.add('funky');
toggle.innerText = 'Turn theme off';
localStorage.setItem('funky', true);
}
});
您可以使用这个小片段和 CSS 变量来创建这样的主题网站,包括深色模式、浅色模式等。
结论
在本教程中,您创建了一个具有明暗模式的主题网站。 要了解有关此代码如何工作的更多信息,请查看我们在 Javascript 或 HTML 上的系列内容。