@Font-face and wrong value of the offsetWidth attribute

一曲冷凌霜 提交于 2019-12-23 07:57:48

问题


I encounter this problem in the latest version of Chromium. After the creation of the first element using a font-family embedded via @font-face I am being handed wrong offsetXyz values. By the time the script is executed, the window.onload hook will already have fired and the font will thus have already been loaded.

This is what the script looks like (schematically):

var e = document.createElement("span");
e["innerText" in e?"innerText":"textContent"] = "fooBar";
e.style.fontFamily = "fontFaceEmbeddedFontFamily";
document.body.appendChild(e);

alert(e.offsetWidth);   // Returns two different values
setTimeout(function() {
  alert(e.offsetWidth); // The latter being correct
}, 1000);

The value is updated "silently". There appears to be no way of waiting for it to correct the values but simply setInterval-check the value and then render the solution. I don't fancy doing dirty stuff like that.

Anyone has any suggestions how to proceed? Happens only when the src: local(" ... ") isn't specified, the issue is hence downloaded-font specific.


回答1:


You have already given the answer yourself. Set src: local() and it will not happen - in general when you use @font-face, stick to the bulletproof syntax, since it was made to overcome browser issues like the one you are butting heads with here.




回答2:


I know is almost a year, but I got this problem too and took me half a day to discover the cause. You can just wait for the entire page to load, instead of using a timeout. The src: local() didn't make any difference for me. So you can use:

<body onload="finished()">

or in jQuery:

$(window).load(
    function() {
        // this only will execute when the entire page is loaded.
    }
);


来源:https://stackoverflow.com/questions/5998137/font-face-and-wrong-value-of-the-offsetwidth-attribute

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!