2010-09-18 63 views
7

我使用jQuery寫這樣的事情:寫作回調函數

$('#current_image').fadeOut(function(){ 
     $('#current_image').attr('src',newImage).show(); 
    }); 

這是可愛的,一旦淡出已經完成,嵌套位執行。

我想在這裏做我自己的功能,將取代fadeOut。我的函數是什麼樣的,以便這段代碼可以工作?

$('#current_image').customFadeOut(function(){ 
     $('#current_image').attr('src',newImage).show(); 
    }); 

回答

3

的關鍵是剛好路過函數引用您定義的原型方法,並結合該傳遞函數$.animate或任何jQuery的動畫功能,你在內部使用。

HTML:

<div id="blah" style="color:#fff; opacity:1; background:black; height:50px; position:relative; ">fsdljfdsjfds</div> 
<a id="click" href="#">fjsd</a> 

JS:

$.fn.customFadeOut = function (callback) { 
    return $(this).animate({ 
     opacity: 0.25, 
     fontSize: "3em", 
     height: 'toggle' 
    }, 5000, function() { 
     callback.apply(this) 
    }); 

} 

$('#click').click(function() { 
    $('#blah').customFadeOut(function() { 
     alert('hi') 

    }) 

})​ 

Live Demo

+1

不能 「功能(){callback.apply(本);}」 的 「回調」 被取代? – 2010-09-18 16:40:12

+0

是的,但除了'callback'之外,可能還需要所有'customFadeOut'的通用功能,因此這種方式更靈活,更明確。我認爲更多功能的演示比簡潔更好。另外,如果有人在沒有函數的情況下調用'customFadeOut'會怎麼樣?然後它會失敗,並且你知道有很多jQuery noobs不知道JS和/或不正確讀取API以知道你必須提供一個參數:p – 2010-09-18 16:41:07