2011-11-30 67 views
3

試圖做一個簡單重複的關鍵幀動畫使用jQueryjQuery的CSS關鍵幀

$(document).ready(function() { 
    $('body').mouseover(function() { 
     var animateloop = 0; 

     $(this).mouseout(function(){ 
      animateloop++; 
     }); 

     while (animateloop !== 1) { 
      $(this).delay(40).css(
       'font-family':'Homestead' 
      ).delay(40).css(
       'font-family':'Arvo' 
      ); 
     } 
    }); 
}); 

我以爲上面這段代碼的工作,但我不明白,jQuery的所有的東西,所以我不能使它發揮作用。

這裏你可以看到這個的jsfiddle:

http://jsfiddle.net/JamesKyle/nPVxb/

+2

什麼不起作用? – locrizak

+0

它沒有做任何事情,我希望它切換字體,你看看jsfiddle嗎? –

+0

它不切換字體,因爲用戶沒有字體(我是其中之一)。它爲我開關顏色 – locrizak

回答

1

一個錯誤首先:

$(this).delay(40).css(
    'font-family':'Homestead' 
) 

冒號:

$(this).delay(40).css(
    'font-family','Homestead' 
) 
+0

好吧,剛剛崩潰瀏覽器 –

+0

我也是。我認爲它很適合瀏覽器在循環中檢查字體系列。 – Shawn31313

+1

是的,因爲while語句沒有永無止境 – island205

1

這作品。

$(this).delay(400).css({ 
    'font-family':'Homestead' 
}); 

的問題是你的.delay(),而不是你的CSS()

.delay()用於這是一個隊列的部分項目,如動畫。

您可以使用.queue()或setTimeout的()

瞭解更多關於此主題:jQuery delay not working

喜歡的東西:

$(document).ready(function() { 
    $('body').mouseover(function() { 

     setTimeout(function() {changefont('arial');}, 400); 
     setTimeout(function() {changefont('courrier new');}, 800); 
     setTimeout(function() {changefont('impact');}, 1200); 

    }); 
}); 


function changefont(fontname) { 
    $('body').css({'font-family':fontname}); 
} 

小提琴:http://jsfiddle.net/nPVxb/74/

0

假設你想一個無限循環,並在一個對象的範圍內工作...

... 
animation : ["first","second","third","etc"], 
frameDelay : 400, 
frameIndex : 0, 
animationTimer : null, 
start : function() { 
    // remember the scope of this object. 
    var handle = this; 
    // start the animation. 
    handle._nextFrame(handle); 
}, 
_nextFrame : function(handle) { 
    // TODO: use frameIndex to render stuff... such as: 
    var animation = handle.animation[frameIndex]; 
    $('body').html('<p>'+animation+'</p>'); 
    // count your frames. You might add stuff to the sequence elsewhere. 
    var numFrames = handle.animation.length; 
    frameIndex = frameIndex < numFrames ? frameIndex++ : 0; 
    handle.animationTimer = window.setTimeout(function() { 
     handle._nextFrame(handle); }, handle.frameDelay); 
}, 
_destroy : function() { 
    var handle = this; 
    clearTimeout(handle.animationTimer); 
}... 

備註: 我使用老式的方法強調界面上的私人功能。你不必以這種方式命名你的變量,而且它們不是私有的。

你會注意到我把「this」存儲到「handle」中。你不能總是依賴這個範圍,比如從一個事件泡泡調用一個對象函數,從一個公共接口調用它,或者在內部引用一個函數到對象。所以我只是把它作爲一個慣例。

把這段代碼放到你的對象中,調用'start'函數,它應該繼續做它的事情,直到你離開頁面。此外,請務必清理遞歸超時,而不是在頁面刷新或頁面導航時出現錯誤。