[英]How do I fade in and fade out one item of a list one at a time?
下面的代碼從firebase數據庫中提取一個列表,該列表位於名為'messagediv'的div id下。此div id上名為'message div'的CSS設置為不顯示。
然后,我運行一個JavaScript腳本,該腳本接受帶有該CSS的項目並將其淡入和淡出。 問題在於,它正在淡入或淡出整個列表,而只反對列表中的一項。
例如,它淡入淡出整個列表:
this is the first item of the list:
this is the second item of the list:
this is the third item of the list:
但是我只希望它一次可以淡入和淡出,所以它會首先淡入淡出:
this is the first item of the list:
然后它會消失這一秒:
this is the second item of the list:
下面是到目前為止我可以淡入和淡出整個列表的代碼,但是我只希望它一次淡入和淡出列表中的一項。
<html>
<head>
<script src='https://cdn.firebase.com/js/client/1.0.17/firebase.js'></script>
<script src='https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js'></script>
<style>
.quotes {display: none;}
</style>
</head>
<body>
<div id='messagesDiv' class="quotes"></div>
<script>
var myDataRef = new Firebase('https://helloworldtest.firebaseio.com');
myDataRef.on('child_added', function(snapshot) {
var message = snapshot.val();
displayChatMessage(message.name, message.text);
});
function displayChatMessage(name, text) {
$('<div/>').text(text).prepend($('<em/>').text(name+': ')).appendTo($('#messagesDiv'));
$('#messagesDiv')[0].scrollTop = $('#messagesDiv')[0].scrollHeight;
};
</script>
<script type="text/javascript" language="javascript">
(function() {
var quotes = $(".quotes");
var quoteIndex = -1;
function showNextQuote() {
++quoteIndex;
quotes.eq(quoteIndex % quotes.length)
.fadeIn(2000)
.delay(2000)
.fadeOut(2000, showNextQuote);
}
showNextQuote();
})();
</script>
</body>
</html>
你想要這樣的東西嗎?
http://jsfiddle.net/prankol57/ZZskf/
您的主要問題是在加載引號之前開始顯示showNextQuote
。 我創建了一個叫做可變started
使項目盡快開始的第一個加載衰落。
另外, $(".quotes")
的長度為1。(只有一個div,其類為“ quotes”)。 我認為您想在.quotes內.quotes
<div>
元素。 這樣就是$(".quotes div")
。 您可能希望添加的每個div元素都具有一個名為“ .quotes”的類。 如果這是您想要的,就需要弄清楚邏輯(應該是不重要的變化)。
這是相關的代碼:
var myDataRef = new Firebase('https://helloworldtest.firebaseio.com');
var started = false;
myDataRef.on('child_added', function (snapshot) {
var message = snapshot.val();
displayChatMessage(message.name, message.text);
});
function displayChatMessage(name, text) {
console.log("before", $(".quotes"));
$('<div/>').text(text).prepend($('<em/>').text(name + ': ')).appendTo($('#messagesDiv'));
console.log("after", $(".quotes"));
$('#messagesDiv')[0].scrollTop = $('#messagesDiv')[0].scrollHeight;
if (!started) {
// We should only start showing next quote when the message has loaded
showNextQuote();
started = true;
}
};
// The loading procedure needs access to this so we can't use an anonymous function
//(function() {
var quoteIndex = -1;
function showNextQuote() {
// We get the div elements inside ".quotes"
var quotes = $(".quotes div");
++quoteIndex;
console.log("Showing next quote", quoteIndex, quotes);
quotes.eq(quoteIndex % quotes.length)
.fadeIn(2000)
.delay(2000)
.fadeOut(2000, showNextQuote);
}
//})();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.