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

通过鼠标移动控制可变字体字重的代码无法运行,如何排查?

问题定位

  • 样式属性赋值错误:原代码直接给DOM节点赋值fontVariationSettings,该属性属于元素的style对象下的样式属性,未加.style的赋值属于自定义属性,完全不会作用到页面样式上,是核心错误。
  • 坐标取值错误:绑定在window上的mousemove事件使用e.offsetX会返回鼠标相对于当前悬停子元素的偏移值,而非整个视口的水平坐标,导致比例计算不符合预期,应该替换为e.clientX获取相对于视口的水平坐标。
  • 缺少可变字体配置:没有为目标元素指定支持wght可变轴的字体,font-variation-settings属性无法生效。
  • 变量未声明:所有变量未使用const/let声明,严格模式下会直接抛出错误阻断代码执行。
  • 数值精度问题:计算出的字重值建议取整,避免部分浏览器解析小数异常。

修复代码

CSS 部分

/* 引入支持可变字重轴的字体,可根据需求替换为对应字体资源 */
@font-face {
  font-family: 'CustomVariableFont';
  src: url('你的可变字体文件路径') format('woff2-variations');
  font-weight: 100 700;
}

#post_title {
  font-family: 'CustomVariableFont', sans-serif;
  font-variation-settings: "wght" 100;
}

JS 部分

const h1 = document.getElementById("post_title");
  
function updateText(e) {
  const multiplierWidth = e.clientX / window.innerWidth;
  const randomWeight = Math.round(multiplierWidth * (700 - 100) + 100);
  h1.style.fontVariationSettings = `"wght" ${randomWeight}`;
}

window.addEventListener("mousemove", updateText);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.10 08:42:03