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

如何在JavaScript中获取自定义字体轴YTRA的属性值

如何获取自定义字体轴「YTRA」的值?

你之所以遇到getPropertyValue is not a function的错误,是因为fontVariationSettings返回的是一个字符串类型的结果,而不是CSSStyleDeclaration对象——只有后者才有getPropertyValue方法。要拿到「YTRA」的值,我们需要手动解析这个字符串。

解决方案:解析字体轴字符串

我们可以写一个简单的解析函数,把返回的字符串转换成键值对对象,这样就能轻松获取任意字体轴的值了:

const one = document.querySelector(".one");
const computedStyle = getComputedStyle(one);
const fontVariationStr = computedStyle.fontVariationSettings;

// 解析字体轴字符串为键值对对象
function parseFontVariations(variationStr) {
  // 按逗号分割每个轴的配置,去除多余空格
  const axisItems = variationStr.split(',').map(item => item.trim());
  const axisMap = {};

  axisItems.forEach(item => {
    // 用正则匹配轴名(带引号)和对应数值
    const matchResult = item.match(/"([A-Za-z0-9]+)"\s*([\d.]+)/);
    if (matchResult) {
      const [_, axisName, axisValue] = matchResult;
      axisMap[axisName] = parseFloat(axisValue);
    }
  });

  return axisMap;
}

// 获取所有字体轴的键值对
const fontAxes = parseFontVariations(fontVariationStr);
// 提取YTRA的值
const ytraValue = fontAxes.YTRA;
console.log(ytraValue); // 输出:908.333

额外补充:滚动时递增YTRA的值

如果要在页面滚动时修改YTRA的值并应用到元素上,可以这样做:

window.addEventListener('scroll', () => {
  // 递增YTRA的值(这里每次加5,你可以调整步长)
  fontAxes.YTRA += 5;
  // 把键值对对象转换回fontVariationSettings要求的字符串格式
  const newVariationStr = Object.entries(fontAxes)
    .map(([axis, value]) => `"${axis}" ${value}`)
    .join(', ');
  // 应用新的字体轴配置
  one.style.fontVariationSettings = newVariationStr;
});

这样就能实现你想要的滚动时动态调整YTRA轴值的效果啦。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.28 19:18:13