在灯光和灯光之间切换暗模式 [英] Switch between Light & Dark Mode
问题描述
我已经使用JavaScript编写了一个脚本,该脚本使我能够检测用户喜欢的颜色模式并使用按钮在明暗模式之间切换.但是必须为每一页调整整个过程.
是否有更简单的解决方案既可以检测首选的颜色模式,又可以使用开关(按钮)在两种模式之间进行切换?由于CSS已经具有 prefers-color-scheme
功能,所以我只需要知道如何以用户身份通过按钮在亮和暗模式之间切换.
这是我当前的代码,用普通的JS编写:
I have written a script using JavaScript that allows me to detect the user's preferred color mode and switch between light and dark mode using a button. But the whole thing has to be adjusted for each page.
Is there a simpler solution to both detect the preferred color mode and switch between the two modes using a switch (button)? Since CSS already has the prefers-color-scheme
feature, I would only need to know how to switch between light and dark mode via a button as a user.
Here's my current code, written in plain JS:
window.onload = detectTheme()
function detectTheme() {
// This detects the device color mode when the user enters the webpage
var theme = document.getElementById("theme");
// Get the ID from the link we want to change
if (window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches) {
theme.href = '/link/to/darkmode/file'
// Changing the file based on the color mode ("dark" file for dark-mode)
}
else if (window.matchMedia && window.matchMedia('(prefers-color-scheme: light)').matches) {
theme.href = '/link/to/lightmode/file'
// Changing the file based on the color mode ("light" file for light-mode)
}
}
var switchLD = document.getElementById("switch");
// This is the ID from the switch button
switchLD.onclick = function toggleTheme() {
var theme = document.getElementById("theme");
// Checks what color-mode file is used
if (theme.getAttribute('href') == '/link/to/lightmode/file') {
theme.href = '/link/to/darkmode/file'
// Changing the file from light to darkmode
}
else if (theme.getAttribute('href') == '/link/to/darkmode/file') {
theme.href = '/link/to/lightmode/file'
// Changing the file from dark to lightmode
}
}
任何答案都会对我有很大帮助.如果有仅使用CSS(或SCSS/SASS)的解决方案,我很乐意使用它.
Any answer would help me a lot. If there is a solution using only CSS (or SCSS / SASS), I'd love to use it.
推荐答案
ThatPurpleGuy的评论实际上回答了我的问题.
The comment by ThatPurpleGuy actually answered my question.
原则上,不使用"prefers-color-scheme".JS仅检测用户使用的是暗还是亮模式,然后调整body标签中的类.根据标签中的类(亮或暗),将应用不同的CSS变量.
In principle, prefers-color-scheme is not used. JS only detects whether the user is using dark or light mode and then adjusts a class in the body tag. Depending on which class is in the tag (light or dark), different CSS variables are applied.
以下是YouTube教程的链接: https://www.youtube.com/观看?v = rXuHGLzSmSE
Here is the link to the YT Tutorial: https://www.youtube.com/watch?v=rXuHGLzSmSE
这篇关于在灯光和灯光之间切换暗模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!