用脚本实现定时换肤可以吗

wen 实用脚本 1

本文目录导读:

用脚本实现定时换肤可以吗

  1. 基于 JavaScript 的简单实现
  2. 使用 CSS 变量 + class 切换
  3. 使用 Node.js 定时脚本(服务端)
  4. 使用 localStorage 持久化用户偏好
  5. HTML 中使用方式
  6. 注意事项

可以,用脚本实现定时换肤完全可行,下面是几种常见的实现方式:

基于 JavaScript 的简单实现

// 主题配置
const themes = {
  morning: {
    '--bg-color': '#ffffff',
    '--text-color': '#333333',
    '--primary-color': '#4a90d9'
  },
  afternoon: {
    '--bg-color': '#f5f5f5',
    '--text-color': '#666666',
    '--primary-color': '#5cb85c'
  },
  night: {
    '--bg-color': '#1a1a1a',
    '--text-color': '#ffffff',
    '--primary-color': '#f0ad4e'
  }
};
// 根据时间获取主题
function getThemeByTime(hour) {
  if (hour >= 6 && hour < 12) return themes.morning;
  if (hour >= 12 && hour < 18) return themes.afternoon;
  return themes.night;
}
// 应用主题
function applyTheme(theme) {
  const root = document.documentElement;
  Object.keys(theme).forEach(key => {
    root.style.setProperty(key, theme[key]);
  });
}
// 定时检查并更新主题
function scheduleThemeUpdate() {
  const now = new Date();
  const hour = now.getHours();
  applyTheme(getThemeByTime(hour));
  // 每分钟检查一次
  setInterval(() => {
    const currentHour = new Date().getHours();
    if (currentHour !== hour) {
      applyTheme(getThemeByTime(currentHour));
    }
  }, 60000);
}
// 启动
scheduleThemeUpdate();

使用 CSS 变量 + class 切换

/* 默认主题 */
:root {
  --bg-color: #ffffff;
  --text-color: #333333;
}
/* 夜间主题 */
body.night-theme {
  --bg-color: #1a1a1a;
  --text-color: #ffffff;
}
/* 早晨主题 */
body.morning-theme {
  --bg-color: #fffff0;
  --text-color: #333333;
}
// 定时切换主题
function switchTheme(theme) {
  const body = document.body;
  body.className = theme;
}
// 设置定时任务
function setupScheduledThemes() {
  const schedule = [
    { time: '06:00', theme: 'morning-theme' },
    { time: '12:00', theme: 'afternoon-theme' },
    { time: '18:00', theme: 'night-theme' }
  ];
  // 检查当前时间
  function checkTime() {
    const now = new Date();
    const currentTime = `${now.getHours().toString().padStart(2, '0')}:${now.getMinutes().toString().padStart(2, '0')}`;
    schedule.forEach(item => {
      if (currentTime === item.time) {
        switchTheme(item.theme);
      }
    });
  }
  // 每分钟检查一次
  setInterval(checkTime, 60000);
  checkTime(); // 初始检查
}
setupScheduledThemes();

使用 Node.js 定时脚本(服务端)

// scheduledTheme.js
const express = require('express');
const http = require('http');
const socketio = require('socket.io');
const app = express();
const server = http.createServer(app);
const io = socketio(server);
// 主题定时更新
function scheduleThemeChange() {
  const cron = require('node-cron');
  // 每天6点切换到日间主题
  cron.schedule('0 6 * * *', () => {
    io.emit('theme-change', { theme: 'day' });
    console.log('切换到日间主题');
  });
  // 每天18点切换到夜间主题
  cron.schedule('0 18 * * *', () => {
    io.emit('theme-change', { theme: 'night' });
    console.log('切换到夜间主题');
  });
  // 每天22点切换到深色主题
  cron.schedule('0 22 * * *', () => {
    io.emit('theme-change', { theme: 'dark' });
    console.log('切换到深色主题');
  });
}
scheduleThemeChange();
// 客户端接收主题更新
io.on('connection', (socket) => {
  console.log('客户端连接');
  // 发送当前主题
  socket.emit('theme-change', { theme: getCurrentTheme() });
});

使用 localStorage 持久化用户偏好

// 带用户自定义偏好的实现
class ThemeManager {
  constructor() {
    this.defaultSchedule = {
      morning: '06:00',
      afternoon: '12:00',
      night: '18:00'
    };
    this.loadUserPreferences();
    this.init();
  }
  loadUserPreferences() {
    const saved = localStorage.getItem('theme_schedule');
    this.schedule = saved ? JSON.parse(saved) : this.defaultSchedule;
  }
  getTheme(hour, minute) {
    const timeStr = `${hour}:${minute}`;
    const morning = this.schedule.morning;
    const afternoon = this.schedule.afternoon;
    const night = this.schedule.night;
    if (timeStr >= night || timeStr < morning) return 'night';
    if (timeStr >= morning && timeStr < afternoon) return 'morning';
    if (timeStr >= afternoon && timeStr < night) return 'afternoon';
  }
  init() {
    // 立即应用当前主题
    const now = new Date();
    this.applyTheme(this.getTheme(now.getHours(), now.getMinutes()));
    // 每分钟检查更新
    setInterval(() => {
      const current = new Date();
      const theme = this.getTheme(current.getHours(), current.getMinutes());
      if (theme !== this.currentTheme) {
        this.applyTheme(theme);
      }
    }, 60000);
  }
  applyTheme(theme) {
    this.currentTheme = theme;
    document.documentElement.setAttribute('data-theme', theme);
    // 触发自定义事件
    document.dispatchEvent(new CustomEvent('themechange', { detail: { theme } }));
  }
  // 允许用户自定义时间
  updateSchedule(newSchedule) {
    this.schedule = {...this.defaultSchedule, ...newSchedule};
    localStorage.setItem('theme_schedule', JSON.stringify(this.schedule));
  }
}
// 使用
const themeManager = new ThemeManager();

HTML 中使用方式

<!DOCTYPE html>
<html>
<head>
  <style>
    [data-theme="morning"] {
      background: #fff;
      color: #333;
    }
    [data-theme="afternoon"] {
      background: #f5f5f5;
      color: #666;
    }
    [data-theme="night"] {
      background: #1a1a1a;
      color: #fff;
    }
  </style>
</head>
<body>
  <button onclick="themeManager.updateSchedule({night: '21:00'})">
    设置夜间模式开始时间
  </button>
  <script src="theme-manager.js"></script>
</body>
</html>

注意事项

  1. 性能优化:避免频繁操作 DOM,使用 CSS 变量可以提高性能
  2. 用户偏好:允许用户自定义主题切换时间
  3. 平滑过渡:添加 CSS transition 实现平滑换肤
  4. 兼容性:确保 CSS 变量在目标浏览器中可用
  5. 服务端同步:如果需要跨设备同步,需要服务端支持

这种方式既实用又易于维护,你可以根据自己的需求选择合适的方案。

抱歉,评论功能暂时关闭!