轻松给网站添加暗黑模式

355 阅读1分钟

「这是我参与11月更文挑战的第6天,活动详情查看:2021最后一次更文挑战」。

你可能在很多网站的右上角看到了一个提供暗黑和高亮模式的切换按钮。

给Web网站或者Web应用添加暗黑模式的基本原理我想大家应该很清楚,事实上主要是用到了css变量,实现起来也非常的简单。

第一步:添加切换开关

上代码:

<!DOCTYPE html>
   <html lang="en" class="theme-light">
<head>

对,只需要在html的标签上添加相应的class,点击切换的时候更换这个css类即可

<div class="theme_switch" onclick="toggleTheme()">
  <img src="/assets/images/moon.svg" id="light_icon">
  <img src="/assets/images/sun.svg" id="dark_icon">
</div>

<script>
    // function to set a given theme/color-scheme
    function setTheme(themeName) {
        localStorage.setItem('theme', themeName);
        document.documentElement.className = themeName;
        if (themeName == 'theme-dark') {
            $('#dark_icon').hide();
            $('#light_icon').show();
        } else {
            $('#dark_icon').show();
            $('#light_icon').hide();
        }
    }

    // function to toggle between light and dark theme
    function toggleTheme() {
        if (localStorage.getItem('theme') === 'theme-dark') {
            setTheme('theme-light');
        } else {
            setTheme('theme-dark');
        }
    }

    // Immediately invoked function to set the theme on initial load
    (function() {
        if (localStorage.getItem('theme') === 'theme-dark') {
            setTheme('theme-dark');
        } else {
            setTheme('theme-light');
        }
    })();
</script>

第二步:编写css变量

示例css:

.theme-light {
    --fill: #f6f6ff;
    --primary: #4969ed;
}

.theme-dark {
    --fill: repeating-linear-gradient(90deg, #000, #000 1px, #1e2029 0, #1e2029 2px);
    --primary: #4969ed;
}

body {
    background:var(--fill); 
}

title {
  color: var(--primary);
}

效果如下

默认亮色模式

暗黑模式

希望帮助到更多需要的小伙伴,好东西大家一起分享!!!