如何检测谷歌网络字体何时准备好并显示在页面中?

Ang*_*gus 8 javascript webfonts

我需要在我的页面中的字体切换到谷歌后立即触发操作.(我正在使用css模式)在字体开关处是否有任何DOM事件被触发?

ric*_*nra 5

David Walsh在此处提供了使用Google Webfonts API的指南:http://davidwalsh.name/google-fonts-api

以下是他的帖子中的一个例子:

WebFontConfig = {
    google: {
        families: [ 'Tangerine', 'Cantarell' ]
    },
    /* Called when all the specified web-font provider modules (google, typekit, and/or custom) have reported that they have started loading fonts. */
    loading: function() {
        // do something
    },
    /* Called when each requested web font has started loading. The fontFamily parameter is the name of the font family, and fontDescription represents the style and weight of the font. */
    fontloading: function(fontFamily, fontDescription) {
        // do something
    },
    /* Called when each requested web font has finished loading. The fontFamily parameter is the name of the font family, and fontDescription represents the style and weight of the font. */
    fontactive: function(fontFamily, fontDescription) {
        // do something
    },
    /* Called if a requested web font failed to load. The fontFamily parameter is the name of the font family, and fontDescription represents the style and weight of the font. */
    fontinactive: function(fontFamily, fontDescription) {
        // do something
    },
    /* Called when all of the web fonts have either finished loading or failed to load, as long as at least one loaded successfully. */
    active: function() {
        // do something
    },
    /* Called if the browser does not support web fonts or if none of the fonts could be loaded. */
    inactive: function() {
        // do something
    }
};

/* async! */
(function() {
var wf = document.createElement('script');
wf.src = ('https:' == document.location.protocol ? 'https' : 'http') + '://ajax.googleapis.com/ajax/libs/webfont/1/webfont.js';
wf.type = 'text/javascript';
wf.async = 'true';
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(wf, s);
})();
Run Code Online (Sandbox Code Playgroud)


The*_*pha 4

不确定这是否是您所需要的,但您可以尝试一下。如果您使用WebFont Loader,那么您可能可以跟踪它。

WebFont Loader 是一个 JavaScript 库,与 Google Web Fonts API 相比,它可以让您更好地控制字体加载。WebFont Loader 还允许您使用多个 Web 字体提供程序。它是由 Google 和 Typekit 共同开发的。

您可以使用一些回调(如 、 等)或检查一些类属性来完成此 loading()操作。active()fontactive(fontFamily, fontDescription)

就到这里了,希望对你有帮助。