简体   繁体   English

刷新页面时关闭暗模式

[英]Dark-mode turned off on refeshing a page

My Dashboard has a dark mode(CSS) but when I refresh the page it turns class BODY dark-mode to light mode!我的仪表板有一个暗模式(CSS),但是当我刷新页面时,它会将 class BODY 暗模式变为亮模式!

How I can save Dark-Mode when the page is refreshed?刷新页面时如何保存暗模式?

NioApp.ModeSwitch = function () {
var toggle = $('.dark-switch');

if ($body.hasClass('dark-mode')) {
  toggle.addClass('active');
} else {
  toggle.removeClass('active');
}

toggle.on('click', function (e) {
  e.preventDefault();
  $(this).toggleClass('active');
  $body.toggleClass('dark-mode');
});};

You can use cookies to store theme and get as you left it like您可以使用 cookies 来存储主题并在您离开时获取

document.cookie = "theme=dark expires=Fri, 31 Dec 9999 23:59:59 GMT /*Not to expire*/" //when switching dark mode

document.cookie = "theme=light expires=Fri, 31 Dec 9999 23:59:59 GMT /*Not to expire*/" //when switching light mode 

And than retrieve this by function而不是通过 function 检索这个

function getCookie(cname) {
    var name = cname + "=";
    var decodedCookie = decodeURIComponent(document.cookie);
    var ca = decodedCookie.split(';');
    for(var i = 0; i <ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') {
        c = c.substring(1);
        }
        if (c.indexOf(name) == 0) {
            return c.substring(name.length, c.length);
        }
    }
    return "";
}

now you only have to get theme from cookies when window ia loaded现在你只需要在 window ia 加载时从 cookies 获取主题

window.addEventListener("load", function() {
    if (getCookie("theme") == "light") {
        //Toggle To Light Theme By Function
    } else if (getCookie("theme") == "dark") {
        //Toggle To Dark Theme By Function
    }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM