使用Javascript / JQuery枚举@ font-face URL

时间:2012-04-20 14:22:48

标签: javascript jquery font-face

有没有办法使用JavaScript或JQuery枚举给定HTML页面的所有@ font-face URL(Web字体URL)?

4 个答案:

答案 0 :(得分:4)

是的,假设您想要找到样式表中指定的所有@ font-faces,而不是HTML文档本身中实际使用的那些。

给出一个合理标准的样式表,如下所示:

@font-face {
    font-family: 'Lobster12Regular';
    src: url('fonts/lobster_1.2-webfont.eot');
    src: url('fonts/lobster_1.2-webfont.eot?#iefix') format('embedded-opentype'),
         url('fonts/lobster_1.2-webfont.woff') format('woff'),
         url('fonts/lobster_1.2-webfont.ttf') format('truetype'),
         url('fonts/lobster_1.2-webfont.svg#Lobster12Regular') format('svg');
    font-weight: normal;
    font-style: normal;

}

@font-face {
    font-family: 'AllerRegular';
    src: url('fonts/aller_std_rg-webfont.eot');
    src: url('fonts/aller_std_rg-webfont.eot?#iefix') format('embedded-opentype'),
         url('fonts/aller_std_rg-webfont.woff') format('woff'),
         url('fonts/aller_std_rg-webfont.ttf') format('truetype'),
         url('fonts/aller_std_rg-webfont.svg#AllerRegular') format('svg');
    font-weight: normal;
    font-style: normal;

}

@font-face {
    font-family: 'AllerBold';
    src: url('fonts/aller_std_bd-webfont.eot');
    src: url('fonts/aller_std_bd-webfont.eot?#iefix') format('embedded-opentype'),
         url('fonts/aller_std_bd-webfont.woff') format('woff'),
         url('fonts/aller_std_bd-webfont.ttf') format('truetype'),
         url('fonts/aller_std_bd-webfont.svg#AllerBold') format('svg');
    font-weight: normal;
    font-style: normal;

}

@font-face {
    font-family: 'AllerLight';
    src: url('fonts/aller_std_lt-webfont.eot');
    src: url('fonts/aller_std_lt-webfont.eot?#iefix') format('embedded-opentype'),
         url('fonts/aller_std_lt-webfont.woff') format('woff'),
         url('fonts/aller_std_lt-webfont.ttf') format('truetype'),
         url('fonts/aller_std_lt-webfont.svg#AllerLight') format('svg');
    font-weight: normal;
    font-style: normal;

}

h1 {
    font-family: 'Lobster12Regular';
}

h2 {
    font-family: 'AllerRegular';
}

然后,下面的HTML(带内联Javascript)或多或少都可以解决问题:

<html>

<head>

<link rel="stylesheet" href="test.css">

</head>

<body>

<h1>Hello</h1>
<h2>Hello</h2>

<script type="text/javascript">

var pattern=/url\(.*?\)/g;
for (var i=0;i<document.styleSheets[0].cssRules.length;i++)
{
    var urls=document.styleSheets[0].cssRules[i].cssText.match(pattern);
    if (urls)
    {
        for (var j=0;j<urls.length;j++)
        {
            alert(urls[j]);
        }
    }
}

</script>

</body>

</html>

有一些警告:

首先,指定@ font-face的主要方法之一依赖于指定src两次,这种技术只会获取第二个src。

我没有测试过这种跨浏览器,但它可以在我的浏览器上运行,并弹出一个包含每个字体网址的警告框。

硬编码[0]使它只查看第一个样式表(在这个例子中只有一个)。如果需要的话,编写另一个循环来遍历所有样式表是相当简单的,但对于这个例子来说似乎有些过分。

答案 1 :(得分:0)

不,不是真的。似乎只有这种技术:http://paulirish.com/2009/font-face-feature-detection/来检测是否可以使用@font-face,但不能检测 正在使用哪种字体。解析所有CSS代码服务器端(或至少服务器端辅助)没有办法做你想要的,而不是只用JS和jQuery。对不起。

答案 2 :(得分:0)

这是我刚刚为自己编写的内容,适用于Chrome,未经其他浏览器测试 - 但对我来说似乎相当标准。

它需要jquery,并将识别正在使用的所有字体及其来源(如果是webfonts)。

注意,它不能充分处理字体的变化(不同的'粗体'版本),也无法处理定义了多种字体的样式(例如:font-family:fonta,fontb,fontc)。

jQuery.fn.elementText = function() {
    return $(this)  
            .clone()
            .children()
            .remove()
            .end()
            .text()
            .replace(/^\s\s*/, '').replace(/\s\s*$/, '')
            ;
};

Font = function(family, src) {
    // In order to properly categorise complex font setups, weight and style need to be 
    // considered as part of a unique font. (TODO)
    this.family = family;
    this.src = src;
    this.weight = null;
    this.style = null;
};

Font.prototype.toString = function() {
    return '[Font ' + this.family + ': ' + this.src + ']';
};


var fontNames = {};
var fontObjects = [];

$(':visible').each(function (k, v) {
    var $v = $(v);
    var font;
    if ($v.elementText().length) {
        font = $v.css('font-family');
        // TODO: seperate by comma, remove quotes
        fontNames[font] = font;
    }
});

for (var sheet=0; sheet < document.styleSheets.length; sheet++)
for (var i=0; i<document.styleSheets[sheet].cssRules.length; i++)
{
    var rule = document.styleSheets[sheet].cssRules[i];
    if (rule instanceof CSSFontFaceRule) {
        if (fontNames[rule.style.fontFamily])
            fontObjects.push(
                    new Font(rule.style.fontFamily, rule.style.src) );
    }
}

fontObjects.forEach( function(v) { console.log(v.toString()); });

示例输出(这里您可以看到当您使用不同的'bold','italic'等字体样式定义时会发生什么的示例):

[Font 'ITC Legacy Sans Std': url(http://localhost/~admin/tmp/fonts/LegacySansStd-BookItalic.otf)]
[Font 'ITC Legacy Sans Std': url(http://localhost/~admin/tmp/fonts/LegacySansStd-Book.otf)]
[Font 'ITC Legacy Sans Std': url(http://localhost/~admin/tmp/fonts/LegacySansStd-MediumItalic.otf)]
[Font 'ITC Legacy Sans Std': url(http://localhost/~admin/tmp/fonts/LegacySansStd-Medium.otf)]
[Font 'ITC Legacy Sans Std': url(http://localhost/~admin/tmp/fonts/LegacySansStd-BoldItalic.otf)]
[Font 'ITC Legacy Sans Std': url(http://localhost/~admin/tmp/fonts/LegacySansStd-Bold.otf)]
[Font 'ITC Legacy Sans Std': url(http://localhost/~admin/tmp/fonts/LegacySansStd-Ultra.otf)]
[Font 'Ocean Sans Std': url(http://localhost/~admin/tmp/fonts/OceanSansStd-LightIta.otf)]
[Font 'Ocean Sans Std': url(http://localhost/~admin/tmp/fonts/OceanSansStd-Light.otf)]
[Font 'Ocean Sans Std': url(http://localhost/~admin/tmp/fonts/OceanSansStd-Book.otf)]
[Font 'Ocean Sans Std': url(http://localhost/~admin/tmp/fonts/OceanSansStd-SemiboldIta.otf)]
[Font 'Ocean Sans Std': url(http://localhost/~admin/tmp/fonts/OceanSansStd-Semibold.otf)]
[Font 'Ocean Sans Std': url(http://localhost/~admin/tmp/fonts/OceanSansStd-Bold.otf)]

答案 3 :(得分:0)

您还可以获取带有变体和URL的字体系列。
以下是jQuery中的代码

var fontArray = [];
$.get("https://www.googleapis.com/webfonts/v1/webfonts?key={your key}&sort=popularity", {}, function (data) {
    var count = 0;
    $.each(data.items, function (index, value) {
        count++
        fontArray.push(value);
    });
});