You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

如何利用localStorage保存作品集网站明暗主题切换状态,解决刷新/跳转后恢复默认浅色模式的问题?

Fixing Theme Persistence with localStorage

Hey Herman, nice work getting the theme toggle up and running! The missing piece here is saving the user's choice to localStorage so it persists across page reloads and navigation. Let's walk through how to add that step by step.

Step 1: Save the theme choice when toggling

Every time the user clicks the theme switcher, we need to store their selected theme in localStorage. We'll use localStorage.setItem() to save a key-value pair (like 'selectedTheme' with a value of 'light' or 'dark').

Step 2: Load the saved theme on page initialization

When the page first loads, we'll check if there's a saved theme in localStorage using localStorage.getItem(). If there is, we'll apply that theme to the body and update the button's content to match. If not, we can fall back to the default light theme (or even respect the user's system preference for dark mode—bonus tip at the end!).

Updated Full JavaScript Code

Here's your modified code with persistence added:

// Wait for the DOM to be fully loaded before running code
document.addEventListener('DOMContentLoaded', function() {
  const button = document.getElementById('themeswitcher');
  
  // Function to apply a theme and update the button
  function applyTheme(theme) {
    if (theme === 'dark') {
      document.body.classList.remove('light-theme');
      button.innerHTML = `<span>Light</span><img src="images/sunrise.png" alt="Choose website theme">`;
    } else {
      document.body.classList.add('light-theme');
      button.innerHTML = `<span>Dark</span><img src="images/moon.png" alt="Choose website theme">`;
    }
    // Save the theme to localStorage
    localStorage.setItem('selectedTheme', theme);
  }

  // Check for saved theme on page load
  const savedTheme = localStorage.getItem('selectedTheme');
  if (savedTheme) {
    applyTheme(savedTheme);
  } else {
    // Fallback to default light theme (or check system preference below)
    applyTheme('light');
  }

  // Handle button click to toggle theme
  button.addEventListener("click", function () {
    const currentTheme = document.body.classList.contains("light-theme") ? 'light' : 'dark';
    // Toggle to the opposite theme
    const newTheme = currentTheme === 'light' ? 'dark' : 'light';
    applyTheme(newTheme);
  });
});

Key Changes Explained

  • We wrapped everything in DOMContentLoaded to make sure elements exist before we try to access them (prevents errors if the script loads before the button).
  • The applyTheme function consolidates the logic for updating the body class and button content, plus saving to localStorage—keeps code DRY (Don't Repeat Yourself).
  • On page load, we check localStorage for a saved theme. If it exists, we apply it; if not, we use the default light theme.
  • The click handler now just determines the new theme and calls applyTheme, which handles all the updates and saving.

Bonus: Respect System Dark Mode Preference

If you want to take it a step further, you can default to the user's system dark mode setting if they haven't explicitly chosen a theme yet. Replace the fallback part with this:

} else {
  // Check system preference for dark mode
  const prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches;
  applyTheme(prefersDark ? 'dark' : 'light');
}

This makes the site feel more personalized for users who have their system set to dark mode by default.

Your HTML button code doesn't need any changes—this should work seamlessly with what you already have. Test it out: toggle the theme, refresh the page, or navigate to another link, and your choice should stick around!

内容的提问来源于stack exchange,提问作者Herman Vulkers

火山引擎 最新活动