我可以使用JavaScript切换暗模式吗?

时间:2019-10-24 13:38:38

标签: javascript html css typescript sass

我正在使用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
})

3 个答案:

答案 0 :(得分:3)

否。

一种解决方法是将所有更改为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: black;
}

然后,您的JavaScript只需要向body元素添加light-modedark-mode类即可强制采用该模式(覆盖默认模式(如果浏览器不支持该功能,或者设置为亮模式)或暗模式的媒体版本。

答案 1 :(得分:0)

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

一种有效的方法是在查询之外的常规类中设置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

答案 2 :(得分:0)

您可以使用此代码

<!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>