当前位置:首页 > JavaScript

js实现换肤

2026-04-03 19:00:35JavaScript

实现方法一:CSS变量切换

通过定义CSS变量并在JavaScript中动态修改变量值实现换肤效果。

:root {
  --primary-color: #3498db;
  --secondary-color: #2ecc71;
  --text-color: #333;
}

.dark-theme {
  --primary-color: #2980b9;
  --secondary-color: #27ae60;
  --text-color: #f5f5f5;
}
function toggleTheme() {
  document.body.classList.toggle('dark-theme');
}

// 初始加载时检查本地存储
if (localStorage.getItem('theme') === 'dark') {
  document.body.classList.add('dark-theme');
}

实现方法二:类名切换

定义不同主题的CSS类,通过切换类名实现换肤。

.light-theme {
  background-color: #fff;
  color: #333;
}

.dark-theme {
  background-color: #222;
  color: #f5f5f5;
}
function switchTheme(themeName) {
  document.body.className = themeName + '-theme';
  localStorage.setItem('theme', themeName);
}

// 初始化主题
const savedTheme = localStorage.getItem('theme') || 'light';
switchTheme(savedTheme);

实现方法三:动态加载CSS文件

通过动态创建link元素加载不同的CSS文件实现换肤。

function loadTheme(themeName) {
  const link = document.createElement('link');
  link.rel = 'stylesheet';
  link.href = `themes/${themeName}.css`;
  link.id = 'theme-style';

  const oldLink = document.getElementById('theme-style');
  if (oldLink) {
    document.head.removeChild(oldLink);
  }

  document.head.appendChild(link);
  localStorage.setItem('theme', themeName);
}

// 初始化加载主题
const currentTheme = localStorage.getItem('theme') || 'default';
loadTheme(currentTheme);

实现方法四:使用CSS预处理器变量

结合Sass/Less等预处理器和JavaScript实现换肤。

js实现换肤

$themes: (
  light: (
    bg: #fff,
    text: #333,
    primary: #3498db
  ),
  dark: (
    bg: #222,
    text: #f5f5f5,
    primary: #2980b9
  )
);
function applyTheme(theme) {
  Object.keys(theme).forEach(key => {
    document.documentElement.style.setProperty(
      `--${key}`,
      theme[key]
    );
  });
}

// 切换主题示例
const themes = {
  light: {
    'bg': '#fff',
    'text': '#333',
    'primary': '#3498db'
  },
  dark: {
    'bg': '#222',
    'text': '#f5f5f5',
    'primary': '#2980b9'
  }
};

applyTheme(themes.dark);

注意事项

  • 主题切换时考虑添加过渡动画提升用户体验
  • 使用localStorage保存用户选择的主题
  • 提供系统主题偏好检测功能
  • 确保所有页面元素都能正确响应主题变化
  • 高对比度主题需要考虑可访问性需求

标签: 换肤js
分享给朋友:

相关文章

js实现分页

js实现分页

实现分页的基本思路 分页功能通常需要处理数据分割、页码生成和用户交互。核心逻辑包括计算总页数、根据当前页截取数据、渲染页码按钮等。 前端分页实现(静态数据) 假设已有全部数据,仅需前端分页展示:…

vue换肤实现

vue换肤实现

实现 Vue 换肤的常见方法 CSS 变量动态切换 通过定义 CSS 变量并在 Vue 中动态修改变量值实现换肤。在根元素(如 :root)或组件中定义变量,通过 JavaScript 动态切换主题…

js实现百叶窗

js实现百叶窗

使用CSS和JavaScript实现百叶窗效果 通过CSS动画和JavaScript事件监听可以实现百叶窗效果。核心思路是将内容区域分割为多个条状元素,通过控制它们的展开/折叠状态来模拟百叶窗。…

js实现图

js实现图

JavaScript 实现图的常用方法 在 JavaScript 中,图(Graph)可以通过多种方式实现,常见的包括邻接表(Adjacency List)和邻接矩阵(Adjacency Matrix…

js节流实现

js节流实现

节流的概念 节流(Throttle)是一种限制函数执行频率的技术,确保函数在一定时间间隔内只执行一次。常用于滚动事件、窗口调整等高频触发的场景。 基础实现方法 使用时间戳判断是否执行函数:…

js 实现滚动

js 实现滚动

实现滚动的方法 使用 window.scrollTo() window.scrollTo() 方法可以滚动到文档中的特定位置。可以指定 x 和 y 坐标,或者使用平滑滚动的选项。 // 滚动到指定位…