Skip to content

isDark

检查当前是否为暗色主题。

语法

ts
isDark(): boolean

返回值

  • boolean - 如果是暗色主题返回 true,否则返回 false

描述

通过解析 userAgent 中的 hxtheme 参数来判断主题模式。当 hxtheme 参数的值为 1 时,表示暗色主题。

示例

typescript
import { isDark } from '@fu/matrix';
// 或
const isDark = window.fuMatrix.isDark;

// 检查当前主题
if (isDark()) {
  console.log('当前是暗色主题');
} else {
  console.log('当前是亮色主题');
}

在页面元素中使用

typescript
import { isDark } from '@fu/matrix';

// 更新页面主题指示器
function updateThemeIndicator() {
  const isDarkMode = isDark();
  const indicator = document.querySelector('.theme-indicator');
  
  if (indicator) {
    indicator.className = `theme-indicator ${isDarkMode ? 'dark' : 'light'}`;
    indicator.textContent = `当前主题:${isDarkMode ? '暗色' : '亮色'}`;
  }
}

// 页面加载时更新
document.addEventListener('DOMContentLoaded', updateThemeIndicator);

动态样式设置

typescript
import { isDark } from '@fu/matrix';

// 根据主题设置样式
const themeColors = {
  background: isDark() ? '#1a1a1a' : '#ffffff',
  text: isDark() ? '#ffffff' : '#333333',
  border: isDark() ? '#333333' : '#e0e0e0'
};

// 应用样式
document.body.style.backgroundColor = themeColors.background;
document.body.style.color = themeColors.text;

环境支持

  • ✅ 浏览器环境
  • ✅ Node.js 环境(安全返回 false

注意事项

  • 在服务端渲染(SSR)环境中会安全返回 false
  • 仅在浏览器环境中才会解析 userAgent
  • 函数具有良好的容错性,异常情况下不会抛出错误