【问题标题】:Implementing automatic dark mode with option to change settings manually [duplicate]使用手动更改设置的选项实施自动暗模式[重复]
【发布时间】:2021-02-17 06:24:39
【问题描述】:

我正在尝试在我的 Wordpress 网站上实现暗模式。到目前为止,我已经创建了一个简单的按钮,允许用户手动更改主题,效果很好。但是,现在我正在尝试将其与基于用户操作系统设置的自动主题检测结合起来。这是我的代码:


jQuery(function($) {
    //Create the cookie object
    var cookieStorage = {
        setCookie: function setCookie(key, value, time, path) {
            var expires = new Date();
            expires.setTime(expires.getTime() + time);
            var pathValue = '';
            if (typeof path !== 'undefined') {
                pathValue = 'path=' + path + ';';
            }
            document.cookie = key + '=' + value + ';' + pathValue + 'expires=' + expires.toUTCString();
        },
        getCookie: function getCookie(key) {
            var keyValue = document.cookie.match('(^|;) ?' + key + '=([^;]*)(;|$)');
            return keyValue ? keyValue[2] : null;
        },
        removeCookie: function removeCookie(key) {
            document.cookie = key + '=; Max-Age=0; path=/';
        }
    };

    //Click on dark mode icon. Add dark mode classes and wrappers. Store user preference through sessions
    $('.dark-mode-button').click(function() {
        //Show either moon or sun
        $('.dark-mode-button').toggleClass('active');
        //If dark mode is selected
        if ($('.dark-mode-button').hasClass('active')) {
            //Add dark mode class to the body
            $('body').addClass('dark-mode');
            cookieStorage.setCookie('MyDarkMode', 'true', 2628000000, '/');
        } else {
            $('body').removeClass('dark-mode');
            setTimeout(function() {
                cookieStorage.removeCookie('MyDarkMode');
            }, 100);
        }
    })

    //Check Storage. Display user preference 
    if (cookieStorage.getCookie('MyDarkMode')) {
        $('body').addClass('dark-mode');
        $('.dark-mode-button').addClass('active');
    }
    
    // Theme depending on system preferences    
if (window.matchMedia("(prefers-color-scheme: dark)").matches) {
        $('body').addClass('dark-mode');
        $('.dark-mode-button').toggleClass('active');
    }
    
    console.log(cookieStorage.getCookie());

})

我不确定从那里去哪里。它应该是这样工作的:如果用户第一次进入我的网站,主题应该根据他的操作系统设置自动调整 - 如果它是黑暗的,那么在黑暗模式下显示网站,反之亦然。但是,如果用户决定通过标题中的专用按钮手动更改主题模式,则不应再遵循他的操作系统设置。我提供的代码就是这样做的,除了最后一部分 - 手动更改的设置不会被保存。现在,当用户手动更改主题时,页面刷新后它会返回到根据他的操作系统设置选择的主题。

【问题讨论】:

标签: javascript jquery


【解决方案1】:

如果您要进行手动覆盖,您可以这样做,以便用户单击手动覆盖并将其更改为相反的颜色模式,然后将其保存在用户想要特定颜色的本地存储中模式。然后当配色方案根据时间发生变化时,它会通过检查用户是否有偏好来取消它。

如果你不知道如何使用本地存储,那么你可以在这里学习如何使用https://www.w3schools.com/jsref/prop_win_localstorage.asp

【讨论】:

  • 好吧,对不起,让我尽快解决这个问题。
猜你喜欢
  • 1970-01-01
  • 2020-07-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-01-25
  • 1970-01-01
相关资源
最近更新 更多