You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用localStorage实现刷新后保留暗黑模式与货币切换器的设置?

Fixing Persistent Dark Mode with localStorage

Hey there! Let's get your dark mode settings to stick even after a page refresh. The main issue with your current code is that it only toggles the theme temporarily—we need to add localStorage to save the user's preference and apply it when the page loads.

First, let's address a small issue in your original code: you're declaring var icon twice, which will overwrite the variable and cause unexpected behavior. We'll fix that by using distinct variable names for your two toggle icons.

Here's the revised, persistent version of your code:

// Initialize theme when the page finishes loading
document.addEventListener('DOMContentLoaded', function() {
  // Grab saved theme from localStorage (default to 'light' if no save exists)
  const savedTheme = localStorage.getItem('theme') || 'light';
  
  // Apply the saved theme to the body
  if (savedTheme === 'dark') {
    document.body.classList.add('dark-theme');
  }
  
  // Update both toggle icons to match the saved theme
  updateThemeIcons(savedTheme === 'dark');
});

// Helper function to update icon sources based on theme state
function updateThemeIcons(isDarkModeActive) {
  const mobileIcon = document.getElementById('icon-phone');
  const desktopIcon = document.getElementById('icon');
  
  const sunIcon = "./assets/images/sun.png";
  const moonIcon = "./assets/images/moon.png";
  
  mobileIcon.src = isDarkModeActive ? sunIcon : moonIcon;
  desktopIcon.src = isDarkModeActive ? sunIcon : moonIcon;
}

// Set up click handlers for both toggle icons
function setupThemeToggle() {
  const mobileIcon = document.getElementById('icon-phone');
  const desktopIcon = document.getElementById('icon');
  
  // Shared toggle logic for both icons
  const toggleTheme = () => {
    // Toggle the dark-theme class on the body
    const isDarkModeActive = document.body.classList.toggle('dark-theme');
    
    // Update icons to reflect the new theme
    updateThemeIcons(isDarkModeActive);
    
    // Save the current theme preference to localStorage
    localStorage.setItem('theme', isDarkModeActive ? 'dark' : 'light');
  };
  
  // Attach click event to both icons
  mobileIcon.addEventListener('click', toggleTheme);
  desktopIcon.addEventListener('click', toggleTheme);
}

// Initialize the theme toggle functionality
setupThemeToggle();

Key improvements explained:

  • Persistent storage: We use localStorage.getItem('theme') to retrieve the user's last selected theme when the page loads, and localStorage.setItem('theme', ...) to save changes whenever they toggle the theme.
  • DOMContentLoaded event: Ensures we don't try to access elements before they're loaded in the DOM, preventing "null" errors.
  • Helper function: updateThemeIcons reduces code duplication by handling icon updates for both mobile and desktop toggles in one place.
  • Fixed variable conflict: We renamed the icons to mobileIcon and desktopIcon to avoid overwriting variables.

Now when users switch to dark mode (or back to light mode), their choice will be saved in their browser. Even if they refresh the page or come back later, the theme will match their last setting.

内容的提问来源于stack exchange,提问作者Hassan Mouhou

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 14:47:31