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

标签 javascript jquery html css

我正在尝试从头开始构建我自己的旋转木马,因为我找不到可以满足我需要的插件。它有一个垂直和水平插件,可以同时双向工作。

无论如何,我决定试一试并尝试构建我自己的。但现在我一直在试图理解为什么我的“下一个”按钮在到达轮播结束时没有消失。

代码如下:

$(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() 从零开始,所以 index 不可能等于或大于 sliderCount。你需要减去一个。

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

您可以使用 toggle 简化那些 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);
}

关于javascript - 为什么我的 Jquery 轮播不会停在最后一张图片上?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19844655/

相关文章:

javascript - 如何使用Jquery动态生成日历控件?

jquery - 重用 jQuery 函数,而不会在不使用该函数的页面上导致错误

html - 付费谷歌站点搜索的奇怪间距

javascript - jQuery 显示/隐藏不起作用

javascript - 目标 ID 而不是 <li>

javascript - 如何使用带有 require 和模块导出的 npm 包作为普通 JS 库

html - CSS full width header (Full width, cannot see body background)

javascript - 输入显示在我的固定标题中

javascript:从 url 中删除特定文本

javascript - 导航到链接 9000 次