JQuery:如何获取字体分配给元素 [英] JQuery: How to get assigned font to element
本文介绍了JQuery:如何获取字体分配给元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
可以在jQuery中检索元素的指定字体吗?
Is it possible to retrieve the assigned font of an element in jQuery?
我们假设有css:
#element
{
font-family: blahblah,Arial;
}
在上面的例子中,Arial字体将被分配给#element。是否有通过JS / JQuery获取信息的方法?
In the above example, Arial font will be assigned to #element. Is there a way to get that information via JS/JQuery?
类似:
$('#element').css('font-family');
只返回 blahblah,Arial;
p>
returns just 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中删除克隆的项目。
edit: had to remove the cloned item from the dom.
再次提示,这还是依赖于元素宽度。 code> $('#element')。detectFont(); // outputs Arial
$('#element').detectFont(); //outputs Arial
这篇关于JQuery:如何获取字体分配给元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文