我正在创建图像轮播
fiddle :https://jsfiddle.net/KyleKatarn/ojxy3o0g/4/
并且轮播中只有两张图像。现在我创建了一个变量 var current = 1
,当用户单击 next
控制按钮时,该变量将获取 current++
。现在我想要 if (current > 2)
我希望变量是 current = 1
这工作得很好。但有一个问题我不想要我的变量current = 3
。因为我只处理两张图像。我不想在图像轮播中看到黑色背景。我只想当它检查第二个图像时,它滚动回到第一个图像
我的 HTML
<div class="slider">
<ul>
<li><img src="http://dogfeathers.com/3d/povray/images/3DGDDDDC.GIF" alt="image" id="a"></li>
<li><img src="http://www.doschdesign.com/images2/Red-DH-VASLA-1.jpg" alt="image"></li>
</ul>
</div>
<div id="slider-nav">
<button data-dir="prev">Previous</button>
<button data-dir="next">Next</button>
</div>
我的JS
(function(){
var imgLength = $('img').length;
var current = 1;
var currentImage = $('img');
$('button').on('click',function(){
if($(this).data('dir') === 'next')
{
current++;
currentImage.animate({
'left':'-=600px'
});
if(current > imgLength)
{
currentImage.animate({
'left':'0px'
});
current = 1;
}
}
if($(this).data('dir') === 'prev'){
current--;
currentImage.animate({
'left':'+=600px'
});
if(current < 1)
{
currentImage.animate({
'left': (600 * (1 - imgLength )) + 'px'
});
current = imgLength;
}
}
});
})();
最佳答案
将默认 animate
操作移至 if
语句后或使用 else
var imgLength = $('img').length;
var current = 1;
var currentImage = $('img');
$('button').on('click',function(){
if($(this).data('dir') === 'next'){
current++;
if(current > imgLength){
currentImage.animate({
'left':'0px'
});
// return here:
return current = 1;
}
// move default action behind if statement (or use ELSE)
currentImage.animate({
'left':'-=600px'
});
// add ELSE here, so that the next IF statement isn't checked unnecessarily:
}else if($(this).data('dir') === 'prev'){
current--;
if(current < 1){
currentImage.animate({
'left': (600 * (1 - imgLength )) + 'px'
});
// return here:
return current = imgLength;
}
// move default action behind if statement (or use ELSE)
currentImage.animate({
'left':'+=600px'
});
}
});
关于javascript - 如何使用 jQuery 图像轮播,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32551398/