2

我需要嗅探 a 的格式,<p>以便将信息传递给 a<iframe>并匹配格式。

我可以使用 jQuery 获取字体

var font = $("p").css('font-family');
var fsiz = $("p").css('font-size');

但是,如果字体系列是网络字体 - 例如“Open Sans”,我还需要找到@font-face加载它的规则的源代码。

我不知道该怎么做。

4

3 回答 3

5

查找所有 css 定义的字体,在此处演示(控制台)。

function getFonts (obj) {
    var o = obj || {},
        sheet = document.styleSheets,
        rule = null,
        i = sheet.length, j;
    while( 0 <= --i ){
        rule = sheet[i].rules || sheet[i].cssRules || [];
        j = rule.length;
        while( 0 <= --j ){
            if( rule[j].constructor.name === 'CSSFontFaceRule' ){ // rule[j].slice(0, 10).toLowerCase() === '@font-face'
                o[ rule[j].style.fontFamily ] = rule[j].style.src;
            };
        }
    }
    return o;
}
于 2012-11-01T05:47:49.327 回答
1

我调整了选择的解决方案,使其在 IE 和 FF 以及 iO 上的 Safari 中也能正常工作。选择的解决方案仅适用于 Chrome。(唉,我不能 - 还 - 为该解决方案添加评论,这就是我将它放在单独的解决方案中的原因。)

function getFonts (obj) {
    var o = obj || {},
        sheets = document.styleSheets,
        rules = null,
        i = sheets.length, j;
    while( 0 <= --i ){
        rules =  sheets[i].cssRules || sheets[i].rules || []; // I swapped those two, IE would go wrong
        j = rules.length;
        while( 0 <= --j ){
            if( rules[j].toString() == "[object CSSFontFaceRule]" ){  // This works in IE and FF too
                o[ rules[j].style.fontFamily ] = rules[j].style.src;
            };
        }
    }
    return o;
}
于 2014-09-09T10:51:52.753 回答
0

作为对Paul S答案的一个小改进,我包含了具有字体粗细和样式的嵌套对象作为键,以检索字体的所有版本。

function getFonts (obj) {
    var o = obj || {},
        sheet = document.styleSheets,
        rule = null,
        i = sheet.length, j;
    while( 0 <= --i ){
        rule = sheet[i].rules || sheet[i].cssRules || [];
        j = rule.length;
        while( 0 <= --j ){
            if( rule[j].constructor.name === 'CSSFontFaceRule' ){
                if (!(rule[j].style.fontFamily in o)) o[ rule[j].style.fontFamily ] = Object.create(null);
                o[ rule[j].style.fontFamily ][ rule[j].style.fontWeight + '-' + rule[j].style.fontStyle ] = rule[j].style.src;
            };
        }
    }
    return o;
}
于 2018-09-17T13:43:51.603 回答