为什么我的 Jquery 轮播不会停留在最后一张图片上

Why my Jquery carousel doesn't stop at the last image?

本文关键字:一张 最后 Jquery 我的 停留在 为什么      更新时间:2023-09-26

我正在尝试从头开始构建自己的轮播,因为我找不到可以做我想做的插件。这是一个垂直和水平插件,可以同时以两种方式工作。

无论如何,我决定试一试并尝试建立自己的。但是现在我只能试图理解为什么我的"下一步"按钮在到达轮播末尾时不会消失。

这是代码:

$(document).ready(function() {
    var sliderWidth = 300; // Give the size of the window
    var sliderV = $('#slide-wrap-vertical'); // Assigns the container that has all the sectiosn that will be scrolled vertically
    var sliderCount = $(sliderV).children().size(); // Gets the size of the verticla slider
    //test();
    $('a.nav-top-prev').on('click',function () {
        $('#slide-wrap-vertical > div').animate({
            top: '+=' + sliderWidth
        }, 500);
        showHideDirection();
    });
    $('a.nav-top-next').on('click', function () {
        $('#slide-wrap-vertical > div').animate({
            top: '-=' + sliderWidth
        }, 500);
        showHideDirection();
    });

    function showHideDirection() {
        $(sliderV).children().each(function(){ // Checks all the children of the vertical carousel

            if ($(this).position().top == 0) { // Finds the index of the children that is currently on view
                if ($(this).index() == 0) { // If its the first one can't scroll back and hides the prev button
                    $('a.nav-top-prev').hide();
                }
                else if ($(this).index() >= sliderCount) { // If its the last one can't scroll forward and hides the next button
                    $('a.nav-top-next').hide();
                }
                else {
                    $('a.nav-top-prev').show();
                    $('a.nav-top-next').show();
                }
            }   
        });
    }

});

http://jsfiddle.net/Dethdoll/WkFVs/8/

因为 sliderCount 是从 1 开始的,而 index() 是从零开始的,所以索引不可能等于或大于 sliderCount。你需要减去一个。

else if ($(this).index() === sliderCount-1)

您可以使用切换来简化那些 if/else 检查

if ($(this).position().top == 0) {
    var index = $(this).index();
    $('a.nav-top-prev').toggle(index!==0);
    $('a.nav-top-next').toggle(index!==sliderCount-1);
}