Skip to content

Instantly share code, notes, and snippets.

@alex1504
Last active May 26, 2017 09:34
Show Gist options
  • Save alex1504/b690342fec2a16321f24da21d599abb0 to your computer and use it in GitHub Desktop.
Save alex1504/b690342fec2a16321f24da21d599abb0 to your computer and use it in GitHub Desktop.
判断浏览器是否存在某种字体
(function() {
/**
* 根据测试字体与基准字体拼接后字体的宽高 和 原来基准字体的宽高进行对比,若不同,则说明测试字体存在
*/
var Detector = function() {
// 传入的字体会和下面三种字体作比较
var baseFonts = ['monospace', 'sans-serif', 'serif'];
// 使用m和w作为测试字符因为它们占据最大宽度
var testString = "mmmmmmmmmmlli";
//测试字体定义为72像素
var testSize = '72px';
var h = document.getElementsByTagName("body")[0];
// 在文档中创建span标签放置测试字体并获取测试字体的宽度
var s = document.createElement("span");
s.style.fontSize = testSize;
s.innerHTML = testString;
var defaultWidth = {};
var defaultHeight = {};
for (var index in baseFonts) {
//获取三种默认字体的宽度及高度
s.style.fontFamily = baseFonts[index];
h.appendChild(s);
defaultWidth[baseFonts[index]] = s.offsetWidth;
defaultHeight[baseFonts[index]] = s.offsetHeight;
h.removeChild(s);
}
function detect(font) {
var detected = false;
for (var index in baseFonts) {
// 测试字体与基准字体拼接后获取字体宽高与基准字体宽高进行比较
s.style.fontFamily = font + ',' + baseFonts[index];
h.appendChild(s);
var matched = (s.offsetWidth != defaultWidth[baseFonts[index]] || s.offsetHeight != defaultHeight[baseFonts[index]]);
h.removeChild(s);
detected = detected || matched;
}
return detected;
}
this.detect = detect;
};
window.Detector = Detector;
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment