[英]jQuery Image Slider issue
我的圖像滑動代碼有問題。 每當我按下“下一個”或“上一個”按鈕時,我都必須單擊3次,直到該按鈕起作用為止,這樣做之后它會完美地工作。 這是我的代碼:
sliderInt=1;
sliderNext=2;
$(document).ready(function(){
$('.slider>img#'+sliderInt).stop().fadeIn(500).delay(0);
startSlider();
});
function startSlider(){
count= $(".slider>img").size();
loop=setInterval(function(){
$(".slider>img#"+sliderInt).stop().fadeOut(500);
if(sliderNext>count){
sliderNext=1;
}
$(".slider>img#"+sliderNext).stop().fadeIn(500).delay(0);
sliderNext++;
sliderInt=sliderNext-1;
},5000);
}
function prev(){
stopLoop();
$(".slider>img#"+sliderInt).stop().fadeOut(500);
sliderInt--;
if(sliderInt<1){
sliderInt=count;
}
$(".slider>img#"+sliderInt).stop().fadeIn(500);
startSlider();
}
function next(){
stopLoop();
$(".slider>img#"+sliderNext).stop().fadeOut(500);
sliderNext++;
if(sliderNext>count){
sliderNext=1;
}
$(".slider>img#"+sliderNext).stop().fadeIn(500);
startSlider();
}
function stopLoop(){
window.clearInterval(loop);
}
這應該工作:
<!doctype html>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript">
var index = 0;
var intervalID = null;
$(document).ready(function() {
$(".slider img").hide();
$(".slider img").first().addClass("active").show();
startloop();
});
function startloop() {
intervalID = setInterval(function() {
next();
}, 5000);
}
function stoploop() {
clearInterval(intervalID);
}
function next() {
$(".slider img.active").removeClass("active").fadeOut(function() {
index++;
if(index == $(".slider img").length) {
index = 0;
$(this)
$(".slider img").first().addClass("active").fadeIn();
} else {
$(this).next().fadeIn().addClass("active");
}
});
}
function prev() {
$(".slider img.active").removeClass("active").fadeOut(function() {
index--
if(index < 0) {
index = $(".slider img").length-1;
$(this)
$(".slider img").last().addClass("active").fadeIn();
} else if(index == $(".slider img").length) {
index = 0;
$(this)
$(".slider img").first().addClass("active").fadeIn();
} else {
$(this).prev().fadeIn().addClass("active");
}
});
}
</script>
</head>
<body>
<div class="slider" >
<a href="#" onclick="prev();stoploop();">prev</a>
<a href="#" onclick="next();stoploop();">next</a>
<br>
<img width="100px" src="http://cdn.wonderfulengineering.com/wp-content/uploads/2014/07/background-wallpapers-7.jpg" title="1"/>
<img width="100px" src="http://cdn.wonderfulengineering.com/wp-content/uploads/2014/07/background-wallpapers-3.jpg" title="2"/>
<img width="100px" src="http://cdn.wonderfulengineering.com/wp-content/uploads/2014/07/background-wallpapers-2.jpg" title="3">
<img width="100px" src="http://cdn.wonderfulengineering.com/wp-content/uploads/2014/07/background-wallpapers-5.jpg" title="4">
</div>
</body>
</html>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.