当前位置:首页 > JavaScript

js实现简易换肤

2026-03-01 12:44:08JavaScript

实现简易换肤的 JavaScript 方法

动态修改 CSS 类名

通过切换 HTML 元素的类名来应用不同的样式。定义多套 CSS 主题类,例如:

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

JavaScript 切换逻辑:

document.getElementById('theme-toggle').addEventListener('click', function() {
  document.body.classList.toggle('theme-dark');
  document.body.classList.toggle('theme-light');
});

使用 CSS 变量动态控制

在根元素定义 CSS 变量:

:root {
  --primary-bg: #ffffff;
  --primary-text: #000000;
}
.dark-theme {
  --primary-bg: #222222;
  --primary-text: #ffffff;
}

通过 JavaScript 切换主题类:

js实现简易换肤

function toggleTheme() {
  document.documentElement.classList.toggle('dark-theme');
}

通过修改 link 标签切换样式表

准备多套 CSS 文件(如 light.css 和 dark.css),动态切换:

function switchTheme(themeName) {
  const link = document.querySelector('link[rel="stylesheet"]');
  link.href = `${themeName}.css`;
}

localStorage 持久化存储主题

结合 localStorage 保存用户选择:

js实现简易换肤

// 初始化时读取
const savedTheme = localStorage.getItem('theme') || 'light';
document.documentElement.className = savedTheme;

// 切换时保存
function toggleTheme() {
  const newTheme = document.documentElement.className === 'dark' ? 'light' : 'dark';
  document.documentElement.className = newTheme;
  localStorage.setItem('theme', newTheme);
}

完整示例代码

HTML 结构:

<button id="theme-toggle">切换主题</button>

JavaScript 实现:

const toggleBtn = document.getElementById('theme-toggle');
const currentTheme = localStorage.getItem('theme') || 'light';
document.documentElement.setAttribute('data-theme', currentTheme);

toggleBtn.addEventListener('click', () => {
  const newTheme = document.documentElement.getAttribute('data-theme') === 'dark' 
    ? 'light' 
    : 'dark';
  document.documentElement.setAttribute('data-theme', newTheme);
  localStorage.setItem('theme', newTheme);
});

对应 CSS:

[data-theme="light"] {
  --bg-color: #ffffff;
  --text-color: #333333;
}
[data-theme="dark"] {
  --bg-color: #222222;
  --text-color: #eeeeee;
}
body {
  background: var(--bg-color);
  color: var(--text-color);
}

标签: 简易换肤
分享给朋友:

相关文章

vue实现网页换肤

vue实现网页换肤

实现网页换肤的方法 在Vue中实现网页换肤功能,可以通过多种方式完成。以下是几种常见的实现方法: 动态切换CSS类名 通过动态绑定类名,切换不同的主题样式。定义一个主题类名,如theme-dark或…

vue实现简易todolist

vue实现简易todolist

实现简易TodoList的步骤 创建Vue项目 使用Vue CLI或Vite快速初始化一个Vue项目。例如通过Vite创建: npm create vite@latest vue-todolis…

js实现简易换肤

js实现简易换肤

实现简易换肤的方法 通过JavaScript实现简易换肤功能,通常涉及动态修改CSS样式或切换CSS文件。以下是几种常见方法: 使用CSS变量切换主题 定义CSS变量并在JavaScript中修改这…

用js实现换肤

用js实现换肤

使用CSS变量实现换肤 通过CSS变量(Custom Properties)可以轻松实现换肤功能。定义不同主题的颜色变量,通过JavaScript切换这些变量。 :root { --primar…

简易实现vue

简易实现vue

简易 Vue 实现核心思路 创建一个极简的 Vue 实现需要理解其核心机制:数据响应式、模板编译和虚拟 DOM。以下是一个简化版实现框架,仅包含核心功能。 数据响应式系统 通过 Object.def…

vue实现换肤

vue实现换肤

Vue 实现换肤功能 Vue 实现换肤功能可以通过多种方式实现,以下介绍几种常见的方法: 动态切换 CSS 类名 通过动态切换 CSS 类名实现换肤,适用于主题样式较少的情况。 <templ…