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

设置fontVariationSettings后无需等待获取正确offsetWidth的方法

动态调整字体可变参数后offsetWidth获取值不准确的问题

通过JavaScript设置元素的fontVariationSettings属性后,立即调用offsetWidth得到的是不准确的数值,该数值会在数毫秒后自动更新为正确值。不仅固定时长的等待方法(比如setTimeout)无法稳定获取准确值,就连MutationObserver也存在延迟,无法及时捕捉到宽度的变化。

相关代码示例:

span.style.fontFamily = 'Gingham, sans-serif'; 
span.textContent = str;
container.appendChild(span);

// 设置字体可变参数
span.style.fontVariationSettings = `'wdth' 140`;

// 立即获取宽度
console.log("now: ", span.offsetWidth) // 输出: now:  81
setTimeout(()=>{
    console.log("after 1000ms: ", span.offsetWidth) // 输出: after 1000ms:  74
},1000)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 19:52:19