JQuery: How to get assigned font to element

后端 未结 4 1563
你的背包
你的背包 2020-12-10 15:20

Is it possible to retrieve the assigned font of an element in jQuery?

Let\'s say there is css:

#element
{
font-family: blahblah,Arial;
}
4条回答
  •  余生分开走
    2020-12-10 15:49

    (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);
    

    edit: had to remove the cloned item from the dom.

    Whipped this up just now, again, it still relies on element width - so your mileage may vary.

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

提交回复
热议问题