当前位置:首页 > JavaScript

js实现换肤

2026-01-13 14:07:52JavaScript

使用CSS变量实现换肤

通过CSS变量可以轻松实现主题切换功能。CSS变量在根元素中定义,通过JavaScript动态修改这些变量值。

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

.dark-theme {
  --primary-color: #2980b9;
  --secondary-color: #27ae60;
  --text-color: #fff;
}

JavaScript切换主题代码:

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

使用类名切换实现换肤

通过为不同主题创建对应的CSS类,切换body元素的类名来改变主题。

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

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

JavaScript切换代码:

function setTheme(themeName) {
  document.body.className = themeName;
}

使用localStorage持久化主题

结合localStorage可以保存用户选择的主题,下次访问时自动加载。

function saveTheme(themeName) {
  localStorage.setItem('theme', themeName);
  document.body.className = themeName;
}

// 页面加载时检查保存的主题
window.addEventListener('DOMContentLoaded', () => {
  const savedTheme = localStorage.getItem('theme') || 'light-theme';
  document.body.className = savedTheme;
});

动态加载CSS文件实现换肤

对于大型项目,可以为不同主题创建单独的CSS文件,动态加载所需样式表。

function loadTheme(themeName) {
  const link = document.createElement('link');
  link.rel = 'stylesheet';
  link.href = `themes/${themeName}.css`;
  document.head.appendChild(link);

  // 移除旧主题
  const oldTheme = document.querySelector('link[data-theme]');
  if(oldTheme) oldTheme.remove();

  link.setAttribute('data-theme', themeName);
}

使用CSS预处理器变量

如果项目使用Sass/Less等预处理器,可以生成多套主题CSS文件。

Sass示例:

$themes: (
  light: (
    bg: #fff,
    text: #333
  ),
  dark: (
    bg: #222,
    text: #fff
  )
);

@mixin theme() {
  @each $theme, $map in $themes {
    .#{$theme}-theme {
      $theme-map: () !global;
      @each $key, $submap in $map {
        $value: map-get($map, $key);
        $theme-map: map-merge($theme-map, ($key: $value)) !global;
      }
      @content;
      $theme-map: null !global;
    }
  }
}

@function themed($key) {
  @return map-get($theme-map, $key);
}

js实现换肤

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

相关文章

js实现轮播

js实现轮播

实现基础轮播效果 使用HTML结构创建轮播容器和图片元素: <div class="carousel"> <div class="carousel-inner">…

js实现分页

js实现分页

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

jquery.js

jquery.js

jQuery 简介 jQuery 是一个快速、简洁的 JavaScript 库,用于简化 HTML 文档遍历、事件处理、动画设计和 Ajax 交互。它的设计宗旨是“Write Less, Do Mor…

vue实现js休眠

vue实现js休眠

Vue 中实现 JavaScript 休眠 在 Vue 中实现 JavaScript 休眠通常需要使用异步方式,以避免阻塞主线程。以下是几种常见方法: 使用 setTimeout 和 Promis…

vue.js实现轮播

vue.js实现轮播

Vue.js 实现轮播功能 使用第三方库(推荐) Vue.js 生态中有许多成熟的轮播组件库,例如 vue-awesome-swiper 或 swiper,它们功能丰富且易于集成。 安装 swipe…

js实现vue

js实现vue

Vue.js 简介 Vue.js 是一个渐进式 JavaScript 框架,用于构建用户界面。其核心库专注于视图层,易于与其他库或现有项目整合。 实现 Vue.js 的基本步骤 安装 Vue.…