英文:
How to get offsetWidth without waiting after setting fontVariationSettings? It is changing after few ms?
问题
如何在通过JavaScript设置fontVariationSettings后立即获取offsetWidth而无需等待?然后它在几毫秒后更改,我无法使用等待。
我看到MutationObserver也有延迟!
span.style.fontFamily = 'Gingham, sans-serif';
span.textContent = str;
container.appendChild(span);
// 设置...
span.style.fontVariationSettings = 'wdth 140';
// 获取...
console.log("当前:", span.offsetWidth) // == 当前: 81
setTimeout(()=>{
console.log("1000毫秒后:", span.offsetWidth) // == 1000毫秒后: 74
},1000)
英文:
How to get offsetWidth without waiting after setting fontVariationSettings via javascript? Then it changes after a few ms and I can't use wait.
I see MutationObserver is also lagging!
span.style.fontFamily = 'Gingham, sans-serif';
span.textContent = str;
container.appendChild(span);
// seting...
span.style.fontVariationSettings = `'wdth' 140`;
// geting...
console.log("now: ", span.offsetWidth) // == now: 81
setTimeout(()=>{
console.log("after 1000ms: ", span.offsetWidth) // == after 1000ms: 74
},1000)
答案1
得分: 1
你不能。您应该等待您的字体被下载并应用以获取更新后的度量信息。
我建议预加载字体,尤其是如果您的代码不是在页面加载时运行。例如,使用数据URL嵌入您的字体。
在我的项目中,我使用了 https://www.npmjs.com/package/fontfaceobserver 来监视字体何时加载,并获取正确的 offsetWidth
。
英文:
You can't. You should wait your font to be downloaded and applied to get the updated metrics.
I suggest to preload font especially if you code works not on a page load. For example embed your font with a data url.
On my project I used https://www.npmjs.com/package/fontfaceobserver to watch when a font is loaded and get a proper offsetWidth
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论