2010-05-20 145 views
0

我想正確的通知彈出的腳本。我不希望彈出窗口在X秒後淡出,或者當用戶單擊消息時淡出。我可以同時獲得兩種效果,但當我嘗試將它們合併時,fadeOut可以工作。這是到目前爲止我的代碼:在jquery設置一個延遲淡出或淡出點擊

function notify(data, type) { 
switch(type) { 
case "success": 
    $('#notify').html(data) 
    .removeAttr("style") 
    .addClass('notifySuccess') 
    .click(function() { 
$("#notify").fadeOut(); 
    }) 
    .delay(5000).fadeOut(); 
break; 
case "error": 
    $('#notify').html(data) 
    .removeAttr("style") 
    .addClass('notifyFailure') 
    .click(function() { 
$("#notify").fadeOut(); 
    }) 
    .delay(5000).fadeOut(); 
break; 
} 
} 

回答

1

你需要有一個.stop()清除延遲從隊列中,像這樣:

function notify(data, type) { 
switch(type) { 
case "success": 
    $('#notify').html(data) 
    .removeAttr("style") 
    .addClass('notifySuccess') 
    .click(function() { 
    $("#notify").stop(true, true).fadeOut(); 
    }) 
    .delay(5000).fadeOut(); 
break; 
case "error": 
    $('#notify').html(data) 
    .removeAttr("style") 
    .addClass('notifyFailure') 
    .click(function() { 
    $("#notify").stop(true, true).fadeOut(); 
    }) 
    .delay(5000).fadeOut(); 
break; 
} 
} 

另外,如果你只對類型successerror ,您可以將此縮減很多,如下所示:

function notify(data, type) { 
$('#notify').html(data) 
    .removeAttr("style") 
    .addClass(type == 'success' ? 'notifySuccess' : 'notifyFailure') 
    .delay(5000).fadeOut() 
    .click(function() { 
    $(this).stop(true, true).fadeOut(); 
    }); 
} 
+0

+1,主要用於重構:-) – 2010-05-20 13:33:17

+0

非常感謝!這正是我想要的。我會按照你的建議減少代碼,再次非常感謝! – JClu 2010-05-20 13:38:42

0

嘗試放置.stop();

.click(function() { 
    $("#notify").stop(true,true).fadeOut(); // also in this part, you may change $("#notify") to $(this) 
})