Besides seeing, is there any way to know which font is currently applied on an HTML element
Consider that I have this CSS rule for an anchor tag:
font-family: Helvetica, Verdana, Calibri, Arial, sans-serif;
Of course by watching at what is rendered in the browser, I can judge which of these fonts has already been used (applied) to format the current anchor element's text.
However, I need to know which font is currently in use via JavaScript (jQuery for example). This jQuery code doesn't help me:
$('#anchor-id').css('font-family');
because it returns 'Helvetica, Verdana, Calibri, Arial, sans-serif;'
. Is there a way to know whic开发者_高级运维h font is in action now?
Update: Based on @MC answer, I created this fiddle and you can check that it's working just nice and quite.
First, you need to test if a font has been installed. I have used some scripts on the internet which will test if a font is installed or not.
Include this snippet of code somewere (thanks to Lucas Smith):
var Font = {
isInstalled : function (name) {
name = name.replace(/['"<>]/g,'');
var body = document.body;
var test = document.createElement('div');
var installed = false;
var teststring = "mmmmmmmmwwwwwwww";
var template = '<b style="display:inline !important; width:auto !important; font:normal 10px/1 \'X\',sans-serif !important">' + teststring + '</b><b style="display:inline !important; width:auto !important; font:normal 10px/1 \'X\',monospace !important">' + teststring + '</b>';
var ab;
if (name) {
test.innerHTML = template.replace(/X/g, name);
test.style.cssText = 'position: absolute; visibility: hidden; display: block !important';
body.insertBefore(test, body.firstChild);
ab = test.getElementsByTagName('b');
installed = ab[0].offsetWidth === ab[1].offsetWidth;
body.removeChild(test);
}
return installed;
}
}
In addition, use the following snippet (I wrote that myself) to get the font-family
value and split that value into parts. Each part is a font, as they are separated by a comma in the CSS code (e.g. font-family: "Nimbus", "Courier New";
):
function workingFont(element) {
var fontString = $(element).css('font-family');
var fonts = fontString.split(",");
for (var f in fonts) {
if (Font.isInstalled(fonts[f])) {
return fonts[f];
}
}
}
As you can see, the first installed font will be returned.
Use workingFont(element)
, where element is the element id, class or tagname. This is part of the jQuery API. Notice you must have jQuery included to get the aforementioned script working.
Update: I created this jsfiddle to test it.
精彩评论