尝试制作一个非常简单的jQuery滑块,但slide1不会转到最后一张图像。它似乎在一个负的直接-1-2 -3 -4循环。
$(".btnPrev").click(function() {
$slideContainer.animate({'margin-left': '+='+width}, animationSpeed, function() {
if (--currentSlide === $slides.length) {
currentSlide = 1;
$slideContainer.css('margin-left', 0);
}
});
});
有人可以帮我解决这个问题吗?
答案 0 :(得分:0)
您的问题是因为您在margin-left
之前应用了currentslide--
。我添加了一个带模数的函数循环。
请尝试:
$(function() {
//settings for slider
var width = 400;
var animationSpeed = 1000;
var currentSlide = 1;
var ifClick = 0;
//cache DOM elements
var $slider = $('#slider');
var $slideContainer = $('.slides', $slider);
var $slides = $('.slide', $slider);
$(".btnNext").click(function() {
if(ifClick == 0){
ifClick = 1;
$slideContainer.animate({'margin-left': '-='+width}, animationSpeed, function() {
if (currentSlide++ === $slides.length-1) {
currentSlide = 1;
$slideContainer.css('margin-left', 0);
}
ifClick = 0;
});
}
});
$(".btnPrev").click(function() {
if(ifClick == 0){
ifClick = 1;
currentSlide--;
if (currentSlide % $slides.length == 0) {
currentSlide = $slides.length-1;
$slideContainer.css('margin-left', -(width*($slides.length-1)));
$slideContainer.animate({'margin-left': '+='+width}, animationSpeed,function(){ifClick=0})
}else{
$slideContainer.animate({'margin-left': '+='+width}, animationSpeed,function(){ifClick=0})
}
}
});
});

body {font-family: helvetica;}
#slider {
width: 400px;
height: 200px;
overflow: hidden;
}
#slider .slides {
display: block;
width: 2400px;
height: 200px;
margin: 0;
padding: 0;
}
#slider .slide {
float: left;
list-style-type: none;
width: 400px;
height: 200px;
}
/* helper css, since we don't have images */
.slide1 {background: red;}
.slide2 {background: blue;}
.slide3 {background: green;}
.slide4 {background: purple;}
.slide5 {background: pink;}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<div class="header">
<h1 class="text-muted">jQuery Basic Slider</h1>
</div>
<div id="slider">
<ul class="slides">
<li class="slide slide1">slide1</li>
<li class="slide slide2">slide2</li>
<li class="slide slide3">slide3</li>
<li class="slide slide4">slide4</li>
<li class="slide slide5">slide5</li>
<li class="slide slide1">slide1</li>
</ul>
</div>
<button class="btnPrev">Previous</button>
<button class="btnNext">Next</button>
</div>
&#13;