[英]How to find out which fonts are included on a page?
I need to get a list of all font names that are available for use on the page via @font-face
declarations (whether in external stylesheets or inline <style>
elements). 我需要获取所有可通过
@font-face
声明在页面上使用的字体名称的列表(无论是在外部样式表还是内联<style>
元素中)。 This is for a script that will be included on pages I do not control. 这是针对我将无法控制的页面上包含的脚本的。
Ideally I'd like to do this without re-downloading all CSS files over AJAX and then parsing them. 理想情况下,我希望不通过AJAX重新下载所有CSS文件然后解析它们就可以做到这一点。
But I can't use the new document.fonts API because I need this to be reasonably cross-browser (even IE7 if possible). 但是我不能使用新的document.fonts API,因为我需要使其成为合理的跨浏览器(如果可能的话甚至是IE7)。
Is there any way to do this without downloading and parsing the CSS? 有什么方法可以执行此操作而无需下载和解析CSS?
I think something like this would be a start: 我认为这将是一个开始:
var sheets = document.styleSheets,
sheet,
rule,
i, j;
for (i = 0; i < sheets.length; i++) {
sheet = sheets[i];
for (j = 0; j < sheet.rules.length; j++) {
rule = sheet.rules[j];
if (typeof(rule.cssText) !== 'undefined' && rule.cssText.indexOf("font-face") !== -1) {
console.log(rule.cssText); // you can parse the font name from rule.cssText here
}
}
Check below code, it might help 检查以下代码,可能有帮助
var ruleFontName = [];
$.each(document.styleSheets, function(sheetIndex, sheet) {
$.each(sheet.cssRules || sheet.rules, function(ruleIndex, rule) {
if (typeof(rule.cssText) !== 'undefined' && rule.cssText.indexOf("font-face") !== -1) {
var fntSrc = (rule.cssText. match(/src: *url\(([^;]+)\);/i) || ["", ""])[1];
var fntName = (rule.cssText.match(/font-family: *([^;]+);/i) || ["", ""])[1];
add(ruleFontName,fntSrc,fntName )
}
});
});
//checking if array values are not repeated
function add(arr, src, name) {
var foundName = arr.some(function (el) {
return el.fntName === name;
});
var foundSrc = arr.some(function (el) {
return el.fntSrc === src;
});
if (!foundName && !foundSrc) {
arr.push({ fntName: name, fntSrc: src });
console.log(arr);
}
}
JSFIDDLE : http://jsfiddle.net/hiteshbhilai2010/dpfpLyq1/47/ JSFIDDLE : http : //jsfiddle.net/hiteshbhilai2010/dpfpLyq1/47/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.