当前位置:首页 > 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元素的类名来改变主题。

js实现换肤

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

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

JavaScript切换代码:

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

使用localStorage持久化主题

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

js实现换肤

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实现跳转

使用 window.location 跳转 通过修改 window.location.href 或直接使用 window.location 实现页面跳转,适用于普通跳转或带参数的 URL。 //…

jquery.js

jquery.js

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

js实现

js实现

实现 JavaScript 功能的方法 在 JavaScript 中实现特定功能通常涉及多个步骤。以下是常见的实现方法: 基础语法和变量声明 使用 let 或 const 声明变量: let co…

js实现拖拽

js实现拖拽

实现拖拽的基本步骤 通过监听鼠标事件(mousedown、mousemove、mouseup)实现拖拽功能。以下是核心代码逻辑: const draggableElement = document.…

js实现复制

js实现复制

使用document.execCommand方法 在较旧的浏览器中,可以使用document.execCommand('copy')实现复制功能。创建一个临时的textarea或input元素,将需要…

js实现轮播图

js实现轮播图

基础轮播图实现 使用HTML、CSS和JavaScript实现一个简单的自动轮播图。HTML结构包含一个容器和多个图片项。 <div class="slider"> <div…