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

添加if else语句后,Google星形按钮点击填充功能失效

解决Google Material星形图标填充切换失效问题

问题原因

  1. element.style的局限性:你用star.style.fontVariationSettings获取的是元素的内联样式,但初始的font-variation-settings是定义在CSS类.star中的,所以第一次点击时这个值是空字符串,根本不满足=== "'FILL' 0"的判断条件,直接走else分支设置为'FILL' 0,等于没做任何有效切换。
  2. 参数值错误:Material Icons的FILL参数有效值是0(未填充)和1(填充),不是你写的10,这个错误也会导致图标显示异常。

解决方案

方案一:使用getComputedStyle获取实际生效样式

修改JavaScript代码,通过getComputedStyle拿到元素当前实际应用的样式,再提取FILL值进行判断:

const star = document.getElementById('star');
star.addEventListener('click', () => {
  const computedStyle = window.getComputedStyle(star);
  // 用正则提取FILL的数值
  const fillMatch = computedStyle.fontVariationSettings.match(/'FILL' (\d)/);
  if (fillMatch && fillMatch[1] === '0') {
    star.style.fontVariationSettings = "'FILL' 1, 'wght' 400, 'GRAD' 0, 'opsz' 24";
  } else {
    star.style.fontVariationSettings = "'FILL' 0, 'wght' 400, 'GRAD' 0, 'opsz' 24";
  }
});

方案二:CSS类切换(更推荐)

这种方法将样式逻辑完全放在CSS中,JS只负责切换类,更符合前端开发的分离原则:

  1. 修改CSS,新增填充状态的类:
.star {
  font-variation-settings: 'FILL' 0, 'wght' 400, 'GRAD' 0, 'opsz' 24;
  background: none;
  border: none;
  color: var(--check-color);
  cursor: pointer;
}

.star.filled {
  font-variation-settings: 'FILL' 1, 'wght' 400, 'GRAD' 0, 'opsz' 24;
}
  1. 简化JavaScript代码:
const star = document.getElementById('star');
star.addEventListener('click', () => {
  star.classList.toggle('filled');
});

额外注意

确保你已经正确引入Google Material Icons字体,否则图标无法正常显示。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 02:06:12