2012-02-12 35 views
0
<div id="messages"> 
<div class="message"> <!-- Visible (5 seconds for hide, show the next, and hide again) --> 
<div class="message" style="display:none;"> <!-- Hidden --> 
<div class="message" style="display:none;"> <!-- Hidden --> 
</div> 

以下(小白)代碼會隱藏創建的5秒後<div>標籤,所以我想隱藏在五秒後每個通知,但是當它是可見的,這件事情如幻燈片播放,但有通知,每通知5秒鐘可見。jQuery的:當它是可見的自動隱藏通知

function setid() { 
    $('.message').each(function() { 
     if($(this).attr('id')==uniqID) { 
      uniqID = Math.floor(Math.random()*9999999); 
     } 
    }); 
} 

console.log = function(message) { 
    console.olog(message); 
    setid(); 
    $('#messages').append('<div id="' + uniqID + '" class="message"> + message + '</div>').show(); 
    $('#' + uniqID).slideDown(200).delay(5000).slideUp(200); 
}; 
+0

Carful單/雙引號。這將不起作用'$('#messages')。append('

+ message + '
').show();'請參閱代碼高亮中的提示?這應該告訴你有什麼不對。 – elclanrs 2012-02-12 18:02:07

+0

class =「message」>'是的,對不起,我總是在示例代碼中寫錯了,我小心翼翼地做了,但是我沒有看到。謝謝。 – Kenny 2012-02-12 18:15:11

+0

然後你應該修復代碼。此外''console.log = function(action,message)'??。而這個'console.olog(message);'? – elclanrs 2012-02-12 18:22:00

回答

3

這其實很簡單:

$(".message").hide().first().show(); 
setTimeout(showNotifications, 5000); 
function showNotifications(){ 
    $(".message:visible").remove(); 
    $(".message").first()show(); 
    if($(".message").length > 0){ 
     setTimeout(showNotifications, 5000); 
    } 
} 

工作原理: 它選擇所有.message元素,並隱藏他們除了第一個。 5秒鐘後,第一條消息將從網頁中刪除,並且以下消息將顯示另外5秒鐘,直到網站中沒有更多通知消息。

想要一些動畫嗎?看看這個:

$(".message").hide().first().show('slow'); 
setTimeout(showNotifications, 5000); 
function showNotifications(){ 
    $(".message:visible").hide('slow', function(){ 
     $(this).remove(); 
     $(".message").first().show('slow'); 
     if($(".message").length > 0){ 
      setTimeout(showNotifications, 5000); 
     } 
    }); 
}​ 

Click here for a working example.

+0

** Papaiatis **我建議你緩存'$(「。message」)'表現。另外,'$(「。message:first」)'比'$(「。message」)要慢。first()' – elclanrs 2012-02-12 18:20:42

+0

@elclanrs'first()'是一個好點,但是緩存'$(「。message 「)'需要更多的維護和代碼,因爲您需要從緩存陣列和DOM中刪除選定的元素。當然,我同意你的表現,但如果我有能力保持簡單,那麼我會這樣做。 – papaiatis 2012-02-12 18:30:54

+0

我不明白。從緩存數組和DOM_中刪除選定的元素意味着什麼?緩存元素將使代碼更容易維護,在這個例子中沒有理由不這樣做。 – elclanrs 2012-02-12 18:34:37

1

你可以嘗試這樣的事情。

var intervalId, 
    $messages = $('#messages').find('.messages:visible'), 
    count = 0; 

$messages.hide();//hide all the messages 

$messages.eq(count).show();//show the first message 

intervalId = setInterval(function(){ 
    $messages.eq(count).hide();//hide the previous message 
    if(count < $messages.length){ 
     $messages.eq(++count).show();//show the next message  
    } 
    else{//all the messages are over clear the interval 
     clearInterval(intervalId); 
    } 
}, 5000); 
+0

謝謝,我會試試看! – Kenny 2012-02-12 18:15:37