2017-06-07 14 views
0

我一直想這幾個小時爲什麼不在淡出和褪色jQuery中?

$('#position-name').html('Successfuly Changed').fadeOut(1000); 
    $('#position-name').html('New Name').fadeIn(); 

我知道它的簡單,但我不知道爲什麼,如果我跑我的代碼只新名稱是守顯示,儘管達內的那些行的原因給定的效果。

它淡出了新名稱然後淡入的新名稱再次

爲什麼不能淡出或顯示成功更改

+0

'.fadeOut([時間] [,完整])'從http://api.jquery.com/fadeout/ –

回答

2

的問題是:您的代碼讀起來就像-change元素html'Successfuly Changed' - 然後同時fadOut()1000其直接切換到'New Name' - 所以你可以看到它​​然後fadeIn()。爲避免你需要使用​​回調函數

$('#position-name').html('Successfuly Changed').fadeOut(1000 ,function(){ 
 
    $(this).html('New Name').fadeIn(); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div id="position-name"></div>

2

兩個淡出一nd fadeIn是異步函數。意思是說,一旦你打電話給他們,這個動作就會在後臺發生,你的代碼立即返回並繼續到下一個語句。

在你的例子中,你在一秒鐘內開始淡出,但一旦它開始,你將替換div的內容並淡入。由於淡出僅運行微秒,所以jquery在內部取消fadeOut操作並且運行淡入淡出,不需要做任何事情。

這兩個函數都帶有第二個參數,它是一個「完整的」回調。你應該如下構造你的代碼。

$('#position-name').html('Successfuly Changed').fadeOut(1000, 
    function() { 
     $('#position-name').html('New Name').fadeIn(); 
    }); 
+0

很好的解釋。我希望我是英語足夠好解釋我的答案是這樣的。+1對於很好的解釋 –

+0

但唯一的事情* jquery內部取消fadeOut動作*而不是它..代碼是'fadeOut()'新內容然後'fadeIn ()' –

1

$("#clickme").click(function() { 
 
var message = $('#position-name'); 
 
    
 
message.html('Successfuly Changed').fadeOut(1000, function() { 
 
    message.html('New Name').fadeIn("slow"); 
 
}); 
 
    
 
});
#box { 
 
    width: 200px; 
 
    height: 50px; 
 
    outline: 2px solid; 
 
    line-height: 50px; 
 
    text-align: center; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script> 
 

 
You can add the next animation in the callback funciton of fadeOut. 
 
After 1 second of the fadeout animation the new fadeIn will start. 
 

 
<div id="box"> 
 
    <div id="position-name"></div> 
 
</div> 
 

 
<button id="clickme">CLICK ME</button>