You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用原生JS统计CSS中[data-theme]属性选择器的总数量

问题原因

你使用的document.querySelectorAll('[data-theme]')是用于查询DOM中带data-theme属性的节点,而非统计CSS样式表中的属性选择器数量,因此无法得到正确的主题总数。

实现方案

要统计CSS中定义的[data-theme]选择器数量,需要遍历页面所有加载的样式表,匹配对应规则即可:

// 统计CSS中[data-theme]主题数量
function countThemeRules() {
  let total = 0;
  // 遍历所有样式表
  for (const sheet of document.styleSheets) {
    try {
      // 遍历单样式表内所有规则
      const rules = sheet.cssRules || sheet.rules;
      for (const rule of rules) {
        // 匹配带[data-theme=前缀的选择器
        if (rule.selectorText?.includes('[data-theme=')) total++;
      }
    } catch (err) {
      // 跨域样式表会触发安全限制,直接跳过
      continue;
    }
  }
  return total;
}
修正后的主题切换函数
function switchTheme() {
  theme++;
  const themeTotal = countThemeRules();
  console.log(themeTotal);
  if (theme > themeTotal) {
    theme = 1;
  }
  localStorage.setItem('theme', theme);
  document.documentElement.setAttribute('data-theme', theme);
}

*注意:如果主题相关CSS写在跨域的外部样式文件中,浏览器会禁止读取规则内容,将主题样式放到同域CSS文件或者页面内联<style>标签中即可正常统计。


内容的提问来源于stack exchange,提问作者patrick

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.20 15:36:03