通过javascript检测正在使用的@ font-face

时间:2012-11-01 05:21:36

标签: javascript jquery css3

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

我可以使用jQuery获取字体

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

但是如果font-family是一个Web字体 - 例如“Open Sans”,我还需要找到加载它的@font-face规则的src。

我不知道该怎么做。

4 个答案:

答案 0 :(得分:5)

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

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

答案 1 :(得分:1)

我将所选择的解决方案改编为IE和FF,以及iOs上的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;
}

答案 2 :(得分:0)

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

   * Ambiguous type variable `t0' arising from a use of `foldr'
  prevents the constraint `(Foldable t0)' from being solved.
  Relevant bindings include
    lengthList :: t0 a -> Integer (bound at lenListFoldr.hs:2:1)
  Probable fix: use a type annotation to specify what `t0' should be.
  These potential instances exist:
    instance Foldable (Either a) -- Defined in `Data.Foldable'
    instance Foldable Maybe -- Defined in `Data.Foldable'
    instance Foldable ((,) a) -- Defined in `Data.Foldable'
    ...plus one other
    ...plus 23 instances involving out-of-scope types
    (use -fprint-potential-instances to see them all)
* In the expression: foldr (\ x s -> s + 1) 0
  In an equation for `lengthList':
      lengthList = foldr (\ x s -> s + 1) 0

答案 3 :(得分:-2)

其他人问了类似的问题,我不确定它是否有帮助。

Can jQuery get all CSS styles associated with an element?