【问题标题】:Can I toggle dark mode using JavaScript?我可以使用 JavaScript 切换暗模式吗?
【发布时间】:2020-05-15 10:37:42
【问题描述】:

我正在使用 prefers-color-scheme: dark 在 CSS 中创建一个深色主题(它适用于 macOS v10.14 (Mojave) 中的 Safari)。有没有办法强制页面在其他不支持它的浏览器上使用我的暗模式代码,如下所示?

document.querySelector('#toggleDarkMode').addEventListener('click', function () {
    -- Force page to use dark mode defined in CSS
})

【问题讨论】:

  • 不是重复的 - 完全不同的问题。 OP 正在询问在不支持 prefers-color-scheme: dark 查询的浏览器中使用 JS 切换暗模式,而链接问题解决了检测和利用查询的问题。

标签: javascript html css typescript sass


【解决方案1】:

没有。

解决方法是将每个更改为 custom property 的属性。

然后你可以这样做:

p {
    color: var(--body-colour);
}

并将其与:

/* default, light scheme */
body {
    --body-colour: black;
}

@media (prefers-color-scheme: dark) {
    body {
        --body-colour: white;
    }
}

body.light-mode {
    --body-colour: black;
}

body.dark-mode {
    --body-colour: white;
}

那么你的 JavaScript 只需要添加一个 light-modedark-mode 类到 body 元素来强制该模式(覆盖默认值(如果浏览器不支持该功能,或者如果它设置为轻模式) 或暗模式媒体版)。

【讨论】:

  • 没有不需要复制所有 CSS 的解决方案吗?
【解决方案2】:

我猜您正在使用媒体查询来了解浏览器/操作系统是否设置为暗模式。 如果较旧的浏览器不理解媒体查询,他们将一起跳过它。这通常用于制作特定于浏览器的“黑客”。

使其工作的一种方法是在通用类中设置查询之外的 sass 代码,您可以将其添加到 <body> 标记中。您可以将此预设存储在 localStorage 或 cookie 中,这样它就不会在页面重置时重置。

关于localStorage:https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage

我会让当前的 sass 代码成为一个 mixin,这样您就不需要再次声明它并使您的代码更易于维护。 更多信息:https://sass-lang.com/documentation/at-rules/mixin

【讨论】:

  • 我不是使用 javascript 操作“浏览器设置”的专家,所以我并不是说这不可能,但我认为这极不可能。
【解决方案3】:

您可以使用此代码

<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
    <title>Dark & Light Mode</title>
    <link rel="stylesheet" href="style.css">
    <style type="text/css">
        @import url("https://fonts.googleapis.com/css?family=Fredoka+One&display=swap");
        html {
            background: var(--backg);
            --btn: #2ab1ce;
            --backg: #fff;
            --colorx: #232323;
            width: 100%;
            height: 100vh;
            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;
        }

        html[data-theme='dartheme'] {
            background: var(--backg);
            --btn: #ea4b3c;
            --backg: #232323;
            --colorx: #fff;
        }

        h1 {
            font-family: 'Fredoka One', cursive;
            font-weight: 300;
            color: var(--colorx);
        }

        h2 {
            font-family: 'Fredoka One', cursive;
            font-weight: 100;
            color: var(--colorx);
        }

        input[type=checkbox] {
            visibility: hidden;
            height: 0;
            width: 0;
        }

        label {
            margin: 0 auto;
            display: flex;
            justify-content: center;
            align-items: center;
            border-radius: 100px;
            position: relative;
            cursor: pointer;
            text-indent: -9999px;
            width: 55px;
            height: 30px;
            background: var(--btn);
        }

        label:after {
            border-radius: 50%;
            position: absolute;
            content: '';
            background: #fff;
            width: 20px;
            height: 20px;
            top: 5px;
            left: 4px;
            transition: ease-in-out 200ms;
        }

        input:checked + label {
            background: #ea4b3c;
        }

        input:checked + label:after {
            left: calc(100% - 5px);
            transform: translateX(-100%);
        }

        html.transition,
        html.transition *,
        html.transition *:before,
        html.transition *:after {
            transition: ease-in-out 200ms !important;
            transition-delay: 0 !important;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>Light & Dark Mode</h1>
        <h2>Demo</h2>

        <input class="container_toggle" type="checkbox" id="switch" name="mode">
        <label for="switch">Toggle</label>
    </div>

    <script src="function.js"></script>
    <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
    <script type="text/javascript">
     var checkbox = document.querySelector('input[name=mode]');

            checkbox.addEventListener('change', function() {
                if(this.checked) {
                    trans()
                    document.documentElement.setAttribute('data-theme', 'dartheme')
                } else {
                    trans()
                    document.documentElement.setAttribute('data-theme', 'lighttheme')
                }
            })

            let trans = () => {
                document.documentElement.classList.add('transition');
                window.setTimeout(() => {
                    document.documentElement.classList.remove('transition');
                }, 1000)
            }
    </script>
</body>
</html>

【讨论】:

    猜你喜欢
    • 2021-08-31
    • 1970-01-01
    • 2021-04-20
    • 1970-01-01
    • 2021-06-25
    • 2020-10-20
    • 2022-01-04
    • 1970-01-01
    • 2010-10-29
    相关资源
    最近更新 更多