【问题标题】:Store CSS or HTML in localStorage在 localStorage 中存储 CSS 或 HTML
【发布时间】:2018-03-21 15:13:20
【问题描述】:

我有这个功能,可以通过一个按钮打开和关闭暗模式。 它检查 dark.css 样式表是否已添加到站点,如果是,则将其删除。如果没有 dark.css,它会加载它并将其附加到头部。

现在我想将此信息存储在 localStorage 中,以便浏览器记住是否应该加载 dark.css。

$(function() {
$('#toggler').click(function(){
    if ($('link[href*="css/dark.css"]').length) {
        $('link[href*="css/dark.css"]').remove();
    }
    else {
        var lightMode = document.createElement('link');
        darkMode.rel="stylesheet";
        darkMode.href="css/dark.css";
        document.getElementsByTagName('head')[0].appendChild(darkMode);
    }
});
})

【问题讨论】:

  • 那么,你有什么尝试?
  • 你试图存储你的值的localStorage在哪里?
  • localStorage.setItem('IsDarkTheme', 'true');localStorage.getItem('IsDarkTheme')
  • 我知道如何设置和获取项目,但我不知道将它们放在代码中的哪个位置
  • 另外请记住,localStorage 并不总是可以访问(私人浏览)。

标签: javascript css stylesheet


【解决方案1】:

您所要做的就是在您的 jQuery 函数中检查 localStorage。最好在函数的前面(这样 DOM 会快速更新,以防您在其他地方有一些密集的代码),尽管不是必需的。

$( function () {

  function appendDarkMode() {

    var darkMode = document.createElement( 'link' );

    darkMode.rel  = 'stylesheet';
    darkMode.href = 'css/dark.css';

    document.getElementsByTagName( 'head' )[ 0 ].appendChild( darkMode );

  }

  // This is run when page is first loaded.
  if ( localStorage ) {

    var useDarkMode = localStorage.getItem( 'useDarkMode' );

    // The boolean we set in the click handler will become a string.
    useDarkMode === 'true' ? appendDarkMode() : localStorage.setItem( 'useDarkMode', false );

  }

  // Theme click handler.    
  $( '.toggler' ).on( 'click', function ( e ) {

    var $darkModeLink = $( 'link[href*="css/dark.css"]' );

    $darkModeLink.length ? $darkModeLink.remove() : appendDarkMode();

    if ( localStorage ) {

      // Note that we're inverting the value here. By the time this
      // is run, we will have changed whether or not `dark.css` is
      // on the page. Which is opposite the initial value of
      // `$darkModeLink`.
      localStorage.setItem( 'useDarkMode', !$darkModeLink.length  );

    }

  } );

} );

【讨论】:

  • 该函数本身可以工作,但它不会来回切换,只会更改一次样式表,并且在重新加载页面时不会保存项目。
  • 刚刚注意到点击处理程序中的一个小错误。该逻辑旨在检查链接元素的存在,但它实际所做的是评估 jQuery 对象的存在。即使没有找到任何元素,我们也总会得到。代码已更新。 localStorage 值检查也已修复以检查字符串。
  • 谢谢,这个函数现在运行得很好,只是 localStorage 不记得它的状态,所以每次重新加载页面时都会重置它。
  • 确保 localStorage 项目的名称相同,使用相同的大小写等。我以前的代码版本之一在名称末尾有一个空格,请确保您的没有那。否则,它应该可以工作。
  • 一个月后回来,我完全理解您的所作所为并使其正常工作。非常感谢!
【解决方案2】:

虽然我认为您的方法不是最好的(根据您放置 JS 逻辑的位置,以这种方式加载可能会产生样式不正确的内容的“闪烁”),但这是我的解决方案(未经测试,但应该可以):

仅供参考:您需要检查 localStorage 的可用性或滚动 pollyfill。见Mozilla Docs

$(function() {
  var themes = {
    light: 'light',
    dark: 'dark'
  };

  var currentTheme = themes.light; // default to light

  function changeTheme(theme) {
    if (!theme || !themes[theme]) return;
    setTheme(theme);

    Object.keys(themes).forEach(function(t) {
      var linkEl = $('link[href*="css/' + t + '.css"]');
      if (linkEl.length && t !== theme) {
        linkEl.remove();
      }
    });
  }

  function setTheme(theme) {
    if (!theme || !themes[theme]) return;

    var linkEl = document.createElement('link');
    linkEl.rel="stylesheet";
    linkEl.href="css/" + theme + ".css";
    document.getElementsByTagName('head')[0].appendChild(linkEl);

    if (localStorage) {
      localStorage.setItem('theme', theme);
    }

    currentTheme = theme;
  }

  if (localStorage) {
    var theme = localStorage.getItem('theme');
    changeTheme(theme);
  } else {
    changeTheme(currentTheme);
  }

  $('#toggler').click(function(){
      switch (currentTheme) {
        case themes.light:
          changeTheme(themes.dark);
          break;
        case themes.dark:
        default:
          changeTheme(themes.light);
          break;
      }
  });
})

【讨论】:

  • 代码尝试加载一个null.css为什么明显找不到
  • @DeeKoul 很好 - 更新了空/未定义检查的答案。
  • 谢谢,错误消失了,但切换器在单击它时不会做任何事情。你能用这个小提琴给我一个修复吗? jsfiddle.net/jrwjd7js
  • @DeeKoul 对此感到抱歉 - 我忘记了我重构主题时使用对象而不是数组,我需要更新迭代器和访问器。 jsfiddle.net/jrwjd7js/6答案也更新了
  • 它仍然对我不起作用。我需要对您的代码进行任何更改吗?单击切换器时,不会将 css 文件添加到标题中。
猜你喜欢
  • 1970-01-01
  • 2011-10-28
  • 2013-06-03
  • 2013-12-23
  • 2023-03-25
  • 2013-02-09
  • 2012-11-13
  • 2012-03-17
  • 1970-01-01
相关资源
最近更新 更多