在javascript / jquery IE和Chrome和FF中阅读@ font-face css

时间:2014-09-08 23:29:57

标签: javascript jquery css font-face

我正在尝试读入一个javascript变量,一个包含@ font-face的(本地)样式表的CSS。 我设法让它在FF en Chrome中运行,但不能在IE或Safari中运行。

这是我的常规(另见jsfiddle - 在不同的浏览器中试用)

function getFonts (obj, doc) {
    // Makes a list of the cssText of all @font-face items.
    var o = obj || {},
    sheets = doc.styleSheets,
    i = sheets.length, j, rules;

    while( 0 <= --i ){
        rules = sheets[i].rules || sheets[i].cssRules || [];
        j = rules.length;

        while( 0 <= --j ){
            // Alternatives for the if below:
            // - (worked only in Chrome): if ( rule[j].constructor.name === 'CSSFontFaceRule' )
            // - if ( rule[j].style.cssText && rule[j].style.cssText.match('src:') )
            // IE just gives NO [object CSSFontFaceRule] !!!
            if( rules[j].toString() == "[object CSSFontFaceRule]" ) {
                // rule.style.fontFamily works in Chrome chrome; Not in FF. For IE I don't know yet.
                fontFamily = rules[j].style.fontFamily || rules[j].style.cssText.match(/font-family\s*:\s*([^;\}]*)\s*[;}]/i)[1]

                // To prevent duplicates we use the cssText as key 
                o[ fontFamily ] = o[ fontFamily ] || {} ;
                o[ fontFamily ][rules[j].style.cssText] = rules[j].style.cssText ;
            }
        }
    }
    return o;
}

我用谷歌搜索了几个小时,但我只是不明白。 IE发现的规则绝不是CSSFontFaceRule类型。我错过了什么吗?

我从网上的某个地方获得了代码并对其进行了修改,以便它也适用于FF(仅适用于Chrome)。 任何人?我知道IE中存在CSSFontFaceRule对象。但你怎么得到它?

PS。我在Windows上,无法测试(最近)Safari;仅在iPad上,它也不起作用。

1 个答案:

答案 0 :(得分:2)

反转检查sheets[i].rulessheets[i].cssRules的顺序 - IE匹配两者,但CSSFontFaceRule仅在后者中找到(在IE9 +中测试)。

http://jsfiddle.net/clintioo/zbpe518k/1/

function getFonts (obj, doc) {
    // Maakt een lijst met de css van alle @font-face items.
    var o = obj || {},
    sheets = doc.styleSheets,
    rule = null,
    i = sheets.length, j;

    while( 0 <= --i ){
        rules = sheets[i].cssRules || sheets[i].rules || [];
        j = rules.length;

        while( 0 <= --j ){
            // Alternatives for the if below:
            // - if ( rule[j].style.cssText && rule[j].style.cssText.match('src:') )
            // - (worked only in Chrome): if ( rule[j].constructor.name === 'CSSFontFaceRule' )
            // IE just gives NO [object CSSFontFaceRule] !!!
            if( rules[j].toString() == "[object CSSFontFaceRule]" ) {
                // rule.style.fontFamily works in Chrome chrome; Not in FF. For IE I don't know yet.
                fontFamily = rules[j].style.fontFamily || rules[j].style.cssText.match(/font-family\s*:\s*([^;\}]*)\s*[;}]/i)[1]

                // To prevent duplicates we use the cssText as key 
                o[ fontFamily ] = o[ fontFamily ] || {} ;
                o[ fontFamily ][rules[j].style.cssText] = rules[j].style.cssText ;
            }
        }
    }
    return o;
}

console.log(getFonts(null, document));