【问题标题】:Dark mode css saving choice暗模式 css 保存选择
【发布时间】:2020-04-28 00:35:09
【问题描述】:

我最近在我的网站上做了一个暗模式就像这样>http://themes.semicolonweb.com/html/canvas/demo-articles.html

但是正如您在刷新页面时看到的那样,它不会保存您的选择,我想用 js 和 localstorage 保存选择,但不能让它工作。 如果您对本地存储有任何建议,这里是我的代码:

    jQuery(document).ready( function($){
    function modeSwitcher( elementCheck, elementParent ) {

        if( elementCheck.filter(':checked').length > 0 ) {
            elementParent.addClass('dark');
            $('.mode-switcher').toggleClass('pts-switch-active');
        } else {
            elementParent.removeClass('dark');
            localStorage.toggled = "";
            $('.mode-switcher').toggleClass('pts-switch-active', false);
        }

    }

    $('.pts-switcher').each( function(){
        var element = $(this),
            elementCheck = element.find(':checkbox'),
            elementParent = $('body');

        modeSwitcher( elementCheck, elementParent );

        elementCheck.on( 'change', function(){
            modeSwitcher( elementCheck, elementParent );
        });
    });
});

【问题讨论】:

  • 我在您的代码中没有看到任何本地存储。你在哪里尝试添加它?什么没用

标签: javascript css local-storage


【解决方案1】:

这里只是给你一个想法,

在暗模式下,单击按钮保存本地存储变量,在亮模式下也是如此。在任何主题上,选择删除另一个本地存储变量。 现在在 document.ready 检查变量并相应地应用类或 CSS, 由于 sn-p 限制,您无法在此处看到此代码,但您可以将其放在本地并使用它,或者只需检查此 codepen Link

$(document).ready(function(){
  		$('#dark').click(function(){
			localStorage.setItem('dark',true);
			localStorage.removeItem('light', false);	
			$('body').css("background-color", '#000');		
  		});
  		$('#light').click(function(){
			localStorage.setItem('light',true);
			localStorage.removeItem('dark',false);	
			$('body').css("background-color", '#fff');
  		});
  		var getLocalDarkVar = localStorage.getItem('dark');
  		if(getLocalDarkVar == "true") {
  			console.log("dark Theme");
  			$('body').css("background-color", '#000');
  		}else {
  			console.log("Light Theme");
  			$('body').css("background-color", '#fff');
  		}

  	});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="dark">Dark Mode</button>
	<button id="light">Light mode</button>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-06-05
    • 2017-07-17
    • 1970-01-01
    • 1970-01-01
    • 2020-12-14
    • 2021-07-24
    相关资源
    最近更新 更多