Am正在尝试创建一个简单的JQuery Slider。每次只能看到一张图片。x秒后,一个新的图像会逐渐消失。唯一的问题是图像没有被显示并且停留在第一张图片上。也许有人能帮我。
迄今为止的代码:HTML
<div id="slideshow">
<span>
<div class="vHolder">
<img src="http://lorempixel.com/150/150/" alt="Slideshow Image 1" class="active" />
</div>
</span>
<span>
<div class="vHolder">
<img src="http://lorempixel.com/150/150/" alt="Slideshow Image 2" />
</div>
</span>
<span>
<div class="vHolder">
<img src="http://lorempixel.com/150/150/" alt="Slideshow Image 3" />
</div>
</span>
<span>
<div class="vHolder">
<img src="http://lorempixel.com/150/150/" alt="Slideshow Image 4" />
</div>
</span>
</div>
JS:
function slideSwitch() {
var $active = $('#slideshow img.active');
if ( $active.length == 0 ) $active = $('#slideshow img:last');
var $next = $active.next().length ? $active.next()
: $('#slideshow img:first');
$active.addClass('last-active');
$next.css({opacity: 0.0})
.addClass('active')
.animate({opacity: 1.0}, 1000, function() {
$active.removeClass('active last-active');
});
}
$(function() {
setInterval( "slideSwitch()", 2500 );
});
和我的工作小提琴:http://goo.gl/4AvUcr
您的滑块无法工作,因为您使用next的方式错误:next是一个同级选择器,因此img的下一个同级将是它自己,因为在带有图像的div中没有其他元素。
如果您更改代码以删除包装div的span标签(不确定为什么您有这些标签,并且它是无效代码),您可以使用以下内容:
function slideSwitch() {
var $active = $('#slideshow .active');
if ($active.length == 0) $active = $('#slideshow > div:last');
var $next = $active.next().length ? $active.next() : $('#slideshow > div:first');
$active.addClass('last-active');
$next.css({
opacity: 0.0
})
.animate({
opacity: 1.0
}, 1000, function() {
$next.addClass('active')
});
$active.css({
opacity: 1.0
})
.animate({
opacity: 0.0
}, 1000, function() {
$active.removeClass('active last-active');
});
}
$(function() {
setInterval("slideSwitch()", 2500);
});
#slideshow {
position: relative;
height: 350px;
}
#slideshow .vHolder {
position: absolute;
top: 0;
left: 0;
z-index: 8;
opacity: 0.0;
}
#slideshow img {
max-width: 150px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="slideshow">
<div class="vHolder" class="active">
<a href="#"><img src="http://lorempixel.com/150/150/city/1" alt="Slideshow Image 1" /></a>
</div>
<div class="vHolder">
<a href="#"><img src="http://lorempixel.com/150/150/city/2" alt="Slideshow Image 2" /></a>
</div>
<div class="vHolder">
<a href="#"><img src="http://lorempixel.com/150/150/city/3" alt="Slideshow Image 3" /></a>
</div>
<div class="vHolder">
<a href="#"><img src="http://lorempixel.com/150/150/city/4" alt="Slideshow Image 4" /></a>
</div>
</div>