我使用 JavaScript 编写了一个脚本,它允许我检测用户的首选颜色模式并使用按钮在明暗模式之间切换。但是整个事情必须针对每一页进行调整。
是否有更简单的解决方案来检测首选颜色模式并使用开关(按钮)在两种模式之间切换?由于 CSS 已经具有该prefers-color-scheme
功能,因此我只需要知道如何以用户身份通过按钮在明暗模式之间切换。
这是我当前的代码,用纯 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)的解决方案,我很乐意使用它。