我想用jQuery制作一个非常简单的texte旋转木马。
当我有3条消息时它看起来有效,但当我有2条或3条以上时它看起来没有。
我如何解决这个问题?
另外,我如何更新消息号码(1?)?
JsFiddle:https://jsfiddle.net/rm7ukmar/
$(function() {
var quotes = $(".message");
var quoteIndex = -1;
function showQuote(change) {
quoteIndex += change;
if (quoteIndex < 0) {
quoteIndex += quotes.length;
}
else if (quoteIndex >= quotes.length) {
quoteIndex -= quotes.length;
}
quotes.stop(true, true).hide().eq(quoteIndex)
.fadeIn(1)
.delay(1)
.fadeOut(1)
.queue(function() { showQuote(1); });
}
showQuote(1);
$('#prev').on('click', function() {
showQuote(-1);
});
$('#next').on('click', function() {
showQuote(1);
});
});
答案 0 :(得分:1)
您可以使用span来绑定值并使用?
来绑定值,从而获取计数而不是$('.sliderCount').text(quotes.length);
。
$(function() {
var quotes = $(".message");
var quoteIndex = -1;
$('.sliderCount').text(quotes.length);
function showQuote(change) {
quoteIndex += change;
if (quoteIndex < 0) {
quoteIndex += quotes.length;
} else if (quoteIndex >= quotes.length) {
quoteIndex -= quotes.length;
}
quotes.stop(true, true).hide().eq(quoteIndex)
.fadeIn(1)
.delay(1000)
.fadeOut(1)
.queue(function() {
showQuote(1);
});
}
showQuote(1);
$('#prev').on('click', function() {
showQuote(-1);
});
$('#next').on('click', function() {
showQuote(1);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="row">
<div class="col-xs-10">
<div class="message">
Message 1
</div>
<div class="message">
Message 2
</div>
<div class="message">
Message 3
</div>
<div class="message">
Message 4
</div>
<div class="message">
Message 5
</div>
</div>
<div class="col-xs-2">
1 of <span class="sliderCount"></span>
<ul class="pagination">
<li>
<a href="#" id="prev">
<</a>
</li>
<li><a href="#" id="next">></a></li>
</ul>
</div>
</div>
更新:检查以下代码段以停止autoplay
$(function() {
var quotes = $(".message");
var quoteIndex = -1;
$('.sliderCount').text(quotes.length);
function showQuote(change) {
quoteIndex += change;
if (quoteIndex < 0) {
quoteIndex += quotes.length;
} else if (quoteIndex >= quotes.length) {
quoteIndex -= quotes.length;
}
quotes.stop(true, true).hide().eq(quoteIndex)
.fadeIn(1)
.delay(1000);
}
showQuote(1);
$('#prev').on('click', function() {
showQuote(-1);
});
$('#next').on('click', function() {
showQuote(1);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="row">
<div class="col-xs-10">
<div class="message">
Message 1
</div>
<div class="message">
Message 2
</div>
<div class="message">
Message 3
</div>
<div class="message">
Message 4
</div>
<div class="message">
Message 5
</div>
</div>
<div class="col-xs-2">
1 of <span class="sliderCount"></span>
<ul class="pagination">
<li>
<a href="#" id="prev">
<</a>
</li>
<li><a href="#" id="next">></a></li>
</ul>
</div>
</div>