すべての要素で動作するようにkmfkの答えが変更されました。ブロック要素が固定または動的な幅を持つため、インライン要素が使用されます。
/**
* Detects the font of an element from the font-family css attribute by comparing the font widths on the element
* @link http://stackoverflow.com/questions/15664759/jquery-how-to-get-assigned-font-to-element
*/
(function($) {
$.fn.detectFont = function() {
var fontfamily = $(this).css('font-family');
var fonts = fontfamily.split(',');
if (fonts.length == 1)
return fonts[0];
var element = $(this);
var detectedFont = null;
fonts.forEach(function(font) {
var clone = $('<span>wwwwwwwwwwwwwwwlllllllliiiiii</span>').css({'font-family': fontfamily, 'font-size':'70px', 'display':'inline', 'visibility':'hidden'}).appendTo('body');
var dummy = $('<span>wwwwwwwwwwwwwwwlllllllliiiiii</span>').css({'font-family': font, 'font-size':'70px', 'display':'inline', 'visibility':'hidden'}).appendTo('body');
//console.log(clone, dummy, fonts, font, clone.width(), dummy.width());
if (clone.width() == dummy.width())
detectedFont = font;
clone.remove();
dummy.remove();
});
return detectedFont;
}
})(jQuery);
ただし、賢明な回避策があります。ご覧ください:http://stackoverflow.com/a/1961519/1064286 –
@donderpiet thats興味深い回避策は、私の問題を解決しません。たとえば、適切なフォントがないときに、どのフォントブラウザのフォールバックをチェックしたいかなどです。 –