簡體   English   中英

使用jQuery知道何時加載@ font-face字體?

[英]Using jQuery to know when @font-face fonts are loaded?

我正在使用@ font-face,但我討厭Firefox顯示默認字體,等待加載@ font-face字體,然后替換它。 因此,整個頁面都會以新字體閃爍。

Webkit瀏覽器只是在加載字體后才顯示文本,而且外觀更加簡潔。

因此,我想知道jQuery是否可以幫助我知道何時加載頁面上的所有數據(包括@ font-face文件),以便隨后顯示文本? 是否有一個jQuery方法告訴我何時加載了所有內容?

我使用此功能-在Safari,Chrome,Firefox,Opera,IE7,IE8,IE9中經過測試:

function waitForWebfonts(fonts, callback) {
    var loadedFonts = 0;
    for(var i = 0, l = fonts.length; i < l; ++i) {
        (function(font) {
            var node = document.createElement('span');
            // Characters that vary significantly among different fonts
            node.innerHTML = 'giItT1WQy@!-/#';
            // Visible - so we can measure it - but not on the screen
            node.style.position      = 'absolute';
            node.style.left          = '-10000px';
            node.style.top           = '-10000px';
            // Large font size makes even subtle changes obvious
            node.style.fontSize      = '300px';
            // Reset any font properties
            node.style.fontFamily    = 'sans-serif';
            node.style.fontVariant   = 'normal';
            node.style.fontStyle     = 'normal';
            node.style.fontWeight    = 'normal';
            node.style.letterSpacing = '0';
            document.body.appendChild(node);

            // Remember width with no applied web font
            var width = node.offsetWidth;

            node.style.fontFamily = font + ', sans-serif';

            var interval;
            function checkFont() {
                // Compare current width with original width
                if(node && node.offsetWidth != width) {
                    ++loadedFonts;
                    node.parentNode.removeChild(node);
                    node = null;
                }

                // If all fonts have been loaded
                if(loadedFonts >= fonts.length) {
                    if(interval) {
                        clearInterval(interval);
                    }
                    if(loadedFonts == fonts.length) {
                        callback();
                        return true;
                    }
                }
            };

            if(!checkFont()) {
                interval = setInterval(checkFont, 50);
            }
        })(fonts[i]);
    }
};

像這樣使用它:

waitForWebfonts(['MyFont1', 'MyFont2'], function() {
    // Will be called as soon as ALL specified fonts are available
});

好的,這很容易。 基本上,我只是將文字設置為:

a.main {visibility: hidden;}

然后添加:

$(window).bind("load", function() {
       $('#nav a.main').addClass('shown');
});

然后確保以下內容也在我的css文件中:

a.main.shown {visibility: visible;}

您不應該使用$(window).bind('load') -這將等待整個頁面加載(也許就是您想要的),而不僅僅是字體。 如果要控制@ font-faces的加載過程,請使用由Google和Typekit開發的WebFont Loader。

您可以將其與Google Font API,typekit和您自己的webfont提供程序一起使用-您(盡管我從來沒有嘗試過,因為我是Typekit用戶。

在此處閱讀有關內容: http : //code.google.com/apis/webfonts/docs/webfont_loader.html和此處: http : //blog.typekit.com/2010/05/19/typekit-and-google/

我使用Google網絡字體(Crete Round Regular和Open Sans Regular加粗)

您可以使用以下任一方法:

var fonts = $.Deferred();
WebFontConfig = { google: { families: [ 'Crete+Round::latin', 'Open+Sans:400,700:latin' ] } , active : function() { fonts.resolve(); } };
(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);
})();
fonts.done(function(){ alert('fonts'); });

或這個 :

WebFontConfig = { google: { families: [ 'Crete+Round::latin', 'Open+Sans:400,700:latin' ] } , active : function() { alert('fonts'); } };
(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);
})();

請注意,在第一個選項中,我使用了jQuery Deferred Object。

也許..

創建一個z-index:-10 div並用大量文本填充(帶有“ normal”字體)。 在document.ready()或其他事件中:

var originalnumber = $( div ).width() + $( div ).height() + $( div ).offset().top + $( div ).offset().left;

$( div ).css( 'font-family', 'MyPrettyWebfont' );

var interval = setInterval( function() {
    var number = $( div ).width() + $( div ).height() + $( div ).offset().top + $( div ).offset().left;

    if ( number !== originalnumber ) {
        // webfont is loaded and applied!
        clearInterval( interval );
    }
}, 10 );

我遇到了同樣的問題。 而且不知何故,我無法讓Google webfont加載器與ttf字體(尤其是中文字體)一起使用,或者在加載字體時發送jquery響應。

因此,我想出了一個更基本的解決方案,在加載頁面后動態更改字體時很有用。 它顯示何時正確加載了字體。

首先,我創建一個虛擬div,然后將其填充為“ abcd”,然后為其設置字體大小40,記錄div的寬度。 當通過按鈕或其他任何東西調用'change font'事件時,它應該跟蹤虛擬div寬度的變化。 寬度更改將表示字體已更改。

HTML代碼

<style>
    @font-face {
     font-family: 'font1';
     src:url('somefont.ttf')  format('truetype');
     }
</style>
<div id="dummy" style="border:1px solid #000; display:inline-block">abdc</div>

<!--simple button to invoke the fontchange-->
<input type="button" onclick="javascript:changefont('font1')" value="change the font"/>

jQuery查詢

//create a variable to track initial width of default font
var trackwidth

//when change font is invoke
function changefont(newfont)
{
   //reset dummy font style
    $('#dummy').css('font-family','initial !important;');
    $('#dummy').css({'font-size':'40px'});
    $('#dummy').html('abcd');

    //ensure that trackwidth is only recorded once of the default font
    if(trackwidth==null)
    {
       trackwidth=( $('#dummy').width());
    }

    //apply new font
    $('#dummy').css('font-family',newfont);
    checkwidth()
}

function checkwidth()
{
   //check if div width changed
   if($('#dummy').width() == trackwidth)
    {
        //if div never change, detect again every 500 milisecs
        setTimeout(checkwidth, 500);
    }
    else
    {
      //do something, font is loaded!
    }
}

我遇到了同樣的問題,我正在嘗試使用readyfunction(),bind()函數和我發現的其他一些函數,但是它們都不起作用。 最后,我找到了一種解決方案,只是在加載動畫之前稍加延遲...就像這樣:

$(document).ready(function() {

setTimeout(function (){
   // The animation
},150);

}); // end ready

我知道這不是最好的解決方案,所以有人可以告訴我一個更好的解決方案嗎?

謝謝!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM