提问者:小点点

jQuery图像滑块-控件


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

null

$(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>

null


共1个答案

匿名用户

在您的代码中,当单击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);
}

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