jQuery图像滑块-控件



我需要帮助。我有一个简单的jQuery滑块,它工作得很好,但我无法解决这种情况:例如,如果我有4个图像,当我到达第四个图像时,我希望能够通过单击"下一个"按钮从第四个转到第一个图像。我该怎么做?

$(document).ready(function(){
$('.next').on('click', function(){
var currentImg = $('.active');
var nextImg = currentImg.next();
if(nextImg.length){
currentImg.removeClass('active').css('z-index', -10);
nextImg.addClass('active').css('z-index', 10);
}
});
$('.prev').on('click', function(){
var currentImg = $('.active');
var prevImg = currentImg.prev();
if(prevImg.length){
currentImg.removeClass('active').css('z-index', -10);
prevImg.addClass('active').css('z-index', 10);
}
});
});
.controls{
display: flex;
}
.control{
padding:20px 60px;
text-align: center;
font-size: 1.2em;
border:1px solid #939393;
font-weight: 600;
cursor:pointer;
font-family: 'Recife';
user-select: none;
}
.prev{
border-right: none;
background-color: #939393;
}
.img-wrapper{
position: absolute;
width:100%;
height:100%;
}
.img-wrapper img{
position: absolute;
width: 100%;
height:100%;
object-fit: cover;
display: none;
}
.img-wrapper img.active{
display: inline-block;
}
.next{
background-color: #fff;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="controls">
<span class="prev control">prev</span>
<span class="next control">next</span>
</div>
<div class="img-wrapper">
<img src="img-one.jpg" alt="one" class="active">
<img src="img-two.jpg" alt="two">
<img src="img-three.jpg" alt="three">
<img src="img-four.jpg" alt="four">
</div>

在您的代码中,当单击next时,它会检查当前图像之后是否有图像。如果不是这样的话,它不会有任何作用。但是,当没有下一个元素时,可以添加else语句返回到第一个项。

更改以下代码。

if(nextImg.length){
currentImg.removeClass('active').css('z-index', -10);
nextImg.addClass('active').css('z-index', 10);
}

currentImg.removeClass('active').css('z-index', -10);
if(nextImg.length){
nextImg.addClass('active').css('z-index', 10);
} else {
var first = $('.img-wrapper img:first-child');
first.addClass('active').css('z-index', 10);
}

当您单击next并将其添加到第一个元素或下一个元素时,此代码将从当前图像中删除.active类。

最新更新