在 localStorage 中存储 CSS 或 HTML

Store CSS or HTML in localStorage

我有这个功能可以通过一个按钮打开和关闭黑暗模式。 它检查 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);
    }
});
})

您所要做的就是检查 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  );

    }

  } );

} );

虽然我不认为你的方法是最好的(以这种方式加载可能会产生 'flash' 样式不正确的内容,具体取决于你放置 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;
      }
  });
})