JQuery:如何为元素分配字体

是否可以在jQuery中检索元素的指定字体?

让我们说有css:

#element { font-family: blahblah,Arial; } 

在上面的示例中,Arial字体将分配给#element。 有没有办法通过JS / JQuery获取该信息?

就像是:

 $('#element').css('font-family'); 

只返回blahblah,Arial;

 (function($) { $.fn.detectFont = function() { var fonts = $(this).css('font-family').split(","); if ( fonts.length == 1 ) return fonts[0]; var element = $(this); var detectedFont = null; fonts.forEach( function( font ) { var clone = element.clone().css({'visibility': 'hidden', 'font-family': font}).appendTo('body'); if ( element.width() == clone.width() ) detectedFont = font; clone.remove(); }); return detectedFont; } })(jQuery); 

编辑 :必须从dom中删除克隆的项目。

刚才鞭打它,再次,它仍然依赖于元素宽度 – 所以你的里程可能会有所不同。

$('#element').detectFont(); //outputs Arial

您可以使用Detector库来执行此操作: http : //www.lalit.org/lab/javascript-css-font-detect/

当浏览器从列表中获取第一个找到的字体时,您应该查看字体列表并尝试检查系统中是否包含此字体。

这是JS / JQuery代码:

 $(function() { var detectFont = function(fonts) { var detective = new Detector(), i; for (i = 0; i < fonts.length; ++i) { if (detective.detect(fonts[i]) !== true) { continue } return fonts[i]; } } var fonts = $('#abcde').css('font-family'); fonts = fonts.split(','); console.log(detectFont(fonts)); }); 

这是现场演示,我准备了: http : //jsfiddle.net/netme/pr7qb/1/

希望,这种方法会对你有所帮助。

修改了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 = $('wwwwwwwwwwwwwwwlllllllliiiiii').css({'font-family': fontfamily, 'font-size':'70px', 'display':'inline', 'visibility':'hidden'}).appendTo('body'); var dummy = $('wwwwwwwwwwwwwwwlllllllliiiiii').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); 
 $('#element').css("font-family", "Arial"); 

试试这个。