带有html5的自动图像滑块的javascript

时间:2015-03-05 09:28:22

标签: javascript jquery html5

以下代码是我的图片滑块的html页面,但在滑动最后一张图片后它不会继续。

<style type="text/css">
#slideshow {
position:relative;
height:300px;
}

#slideshow IMG {
position:absolute;
top:0;
left:0;
z-index:8;
}

#slideshow IMG.active {
z-index:10;
}

#slideshow IMG.last-active {
z-index:9;
}
</style>'


<script>
function slideSwitch() {
    var $active = $('div#slideshow IMG.active');
    var $next = $active.next();    

    $next.addClass('active');

}

$(function() {
    setInterval( "slideSwitch()", 5000 );
});
</script>'

<body>
<div id="slideshow" style="height:300px; width:100%">
<img src="${context:layout/images/images.jpeg}" title="Funky roots"     style="position:absolute; height:300px; width:100%;" class="active"/>
<img src="${context:layout/images/police.jpg}" title="The long and  winding road" style="position:absolute; height:300px; width:100%;"/>
<img src="${context:layout/images/viper_1.jpg}" title="Happy trees"   style="position:absolute; height:300px; width:100%;"/>
</div>
</body>

从这段代码中,如何在最后一张图片后自动滑动并继续下一张幻灯片?

1 个答案:

答案 0 :(得分:0)

您不要将last-active类添加到最后一个元素。因此,每个元素都有active类,每个元素都有z-index: 10

在对代码进行一些工作后,为您获得了这个新的JS:

function slideSwitch() {
  var $active = $('div#slideshow IMG.active');
  var $next = $active.next();    
  $active.addClass('last-active');
  $active.removeClass('active');
  if($next.length == 0) {
    $next = $('div#slideshow IMG').first(); //at the end we need to select the first element, because there is no next()
  }
  $next.removeClass('last-active');
  $next.addClass('active');
}

编辑:

回答你的评论:

在滑块的第一轮之后,类看起来像这样:

<img ... class="last-active"/>
<img ... class="last-active"/>
<img ... class="active"/>

当我们输入代码$active包含最后div$next为空时,因为没有下一个元素。

此时我们必须告诉代码,下一个元素将是第一个元素。 $next = $('div#slideshow IMG').first();只需选择我们要重新开始的第一个div。