【问题标题】:How to find out which fonts are included on a page?如何找出页面中包含哪些字体?
【发布时间】:2014-11-27 20:20:32
【问题描述】:

我需要通过@font-face 声明(无论是在外部样式表中还是内联<style> 元素中)获取可在页面上使用的所有字体名称的列表。这是针对将包含在我无法控制的页面上的脚本。

理想情况下,我希望这样做无需通过 AJAX 重新下载所有 CSS 文件然后对其进行解析。

但我不能使用新的document.fonts API,因为我需要它是合理的跨浏览器(如果可能的话,甚至是 IE7)。

有什么方法可以在不下载和解析 CSS 的情况下做到这一点?

【问题讨论】:

标签: javascript fonts font-face


【解决方案1】:

我认为这样的事情将是一个开始:

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
    }
}

【讨论】:

    【解决方案2】:

    检查下面的代码,它可能会有所帮助

    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/

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-10-11
      • 2018-01-05
      • 2014-03-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多