Is it possible to detect when a browser is using a fallback font instead of the primary one specified in the CSS?

怎甘沉沦 提交于 2019-12-21 07:24:22

问题


If a character is entered in a text field and the currently applied font does not support that character, a backup font is used for that character. Is it possible to tell via Javascript or some other means when this is happening? Trying to create a script which alerts the user if a certain character is not supported by the font. Thanks for your help!


回答1:


This sounds like a job for something like fontkit.js or opentype.js, or even Font.js, all of which can test fonts for glyph support. System fonts are not covered this way (Font.js might work, it'll probably report a width 0 for the tested glyph) but then these are typically the "web safe" fonts, of which we already know exactly which glyphs are supported because everyone uses the same ones. For testing "holes" in a custom font, though, any of the previously mentioned three should already do what you intended to implement.




回答2:


Checking the width of the character in the font, and comparing it with the fallback, you can infer if it is using the fallback font. This test is probably not 100% reliable, but you can do something like:

var text = $(".main-text").html();
var chars = text.split("");
for(var i = 0, len = chars.length; i < len; i++){
	var str = chars[i]; str+=str;str+=str;str+=str;
	$("#test1, #test2").html(str);
	var w1 = $("#test1").width();
	var w2 = $("#test2").width();
	if(w1 == w2 && w1 != 0){
		alert("char not supported " + chars[i]);
	}
}
.main-text {
  width: 50%;
  height: 300px;
  font-family: Impact, sans-serif;
  font-size: 16px;
}
#test1, #test2 {
  position: fixed;
  top: -100px;
  font-size: 16px;
}
#test1 {
  font-family: Impact, sans-serif;
}
#test2 {
  font-family: sans-serif;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea class="main-text">
Serif Font
This E is not supported: ể
</textarea>
<span id="test1"></span>
<span id="test2"></span>

jsfiddle



来源:https://stackoverflow.com/questions/35609728/is-it-possible-to-detect-when-a-browser-is-using-a-fallback-font-instead-of-the

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