mootools
There's a very interesting piece of code on Google Code called FontAvailable which does a jQuery-based JavaScript check on a string to check whether or not your system has a specific font based upon its output width. I've ported this functionality to MooTools.
Google代码上有一个非常有趣的代码,叫做FontAvailable ,它对字符串进行基于jQueryJavaScript检查,以根据系统的输出宽度来检查系统是否具有特定的字体。 我已将此功能移植到MooTools。
MooTools JavaScript (The MooTools JavaScript)
var FontChecker = new Class({
/* implements */
Implements: [Options],
/* options */
options: {
fakeFont: '__RUBBUSH_FONT__',
testString: 'abcdefghijklmnopqrstuvwxyz'
},
/* initialization */
initialize: function(options) {
//set options
this.setOptions(options);
},
/* a method that does whatever you want */
check: function(desiredFont) {
/* create a hidden element */
var element = new Element('span',{
styles: {
visibility: 'hidden',
'font-family': this.options.fakeFont
},
html: this.options.testString
}).inject(document.body);
/* apply a fake font, get width */
var width = element.getCoordinates().width;
/* apply desired font */
element.setStyle('font-family', desiredFont);
var new_width = element.getCoordinates().width;
/* take our temp element out of the DOM */
element.dispose();
/* compare widths to see check if font is available */
return (width !== new_width);
}
});
My code follows the same logic as FontAvailable:
我的代码遵循与FontAvailable相同的逻辑:
- inject a hidden inline element with some garbage text and a fake font 向隐藏的内联元素注入一些垃圾文本和假字体
- record the calculated width of the element 记录元素的计算宽度
- set the element's font to the desired font 将元素的字体设置为所需的字体
- compare the widths and return whether they are the same 比较宽度并返回它们是否相同
用法 (The Usage)
/* when the dom is ready */
window.addEvent('domready',function() {
var fc = new FontChecker();
/* use it...or lose it? */
$('start').addEvent('click',function() {
$$('#font-list li').each(function(el) {
el.setStyle('color', fc.check(el.get('text')) ? 'green' : 'red');
});
});
});
You may check as many fonts as you'd like using one instance by using the check() method.
通过使用check()方法,您可以使用一个实例检查任意多个字体。
The accuracy of this type of check can never be 100% because two fonts could theoretically have the same calculated width. This methods does, however, provide a fairly accurate result.
这种类型的检查的准确性永远不能达到100%,因为两种字体理论上可以具有相同的计算宽度。 但是,此方法确实提供了相当准确的结果。
mootools