设置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
相关产品推荐
相关产品推荐

