使用 jQuery "swipe" 函数导航图像数组

Using jQuery "swipe" function to navigate an array of images

我正在构建一个简单的幻灯片放映,在计算机上查看时通过按钮控制,在触摸屏设备上通过滑动手势控制。 This is a demo with 3 images

每张图片及其相应的说明和导航都包含在一个 div 中。这是第一个:

<div class="item" id="1">
    <img src="...">
    <div class="caption">
        caption 1
    </div>
    <div class="navigation">
        <a href="#" id="1prev">&lt</a> 1 / 3 <a href="#" id="1next">&gt</a>
    </div>
</div>

使用 "click" 和 "swipeleft / swiperight" 函数显示或隐藏这些 div。

$(document).ready(function () {
    $("#1prev").click(function () {
        $("#1").hide();
        $("#3").show();
    });
    $("#1").on("swipeleft", function () {
        $("#1").hide();
        $("#3").show();
    });
    $("#1next").click(function () {
        $("#1").hide();
        $("#2").show();
    });
    $("#1").on("swiperight", function () {
        $("#1").hide();
        $("#2").show();
    });
});

幻灯片总共包含多达 40 张图片。有没有办法压缩脚本?这是一个相对有效且易于访问的解决方案吗?代码写对了吗?可以改进吗?

你可以这样做:

对于项目,我已将 类 分配给上一个和下一个按钮而不是 ID。

<div class="item" id="1">
    <img src="http://www.leecorbin.co/img1.jpg" width="50%" />
    <div class="caption">caption 1</div>
    <div class="navigation"> 
        <a href="#" class="prevBtn">&lt</a> 
        1 / 3 
        <a href="#" class="nextBtn">&gt</a>
    </div>
</div>

然后在脚本中,在 pagecreate

隐藏所有项目,只显示第一个。 为项目上的 swipeleft 和 swiperight 添加处理程序。 为导航按钮添加点击处理程序 在这些处理程序中,确定我们前进的方向以及我们当前在哪张幻灯片上。 调用传递方向和当前幻灯片的函数;它确定要显示的下一张幻灯片并进行转换。

$(document).on("pagecreate", "#page1", function () {
    $(".item").hide().first(0).show();

    $(document).on("swipeleft swiperight", ".item", function (e) {
        var dir = 'prev';
        if (e.type == 'swipeleft') {
            dir = 'next';
        }
        GoToNextSlide($(this), dir);
    });

    $(document).on("click", ".navigation > a", function (e) {
        var dir = 'prev';
        if ($(this).hasClass("nextBtn")) {
            dir = 'next';
        }
        var $item = $(this).closest(".item");
        GoToNextSlide($item, dir);
    });

});

function GoToNextSlide($item, direction) {
    var $next;
    if (direction == 'next') {
        if ($item.next().length > 0) {
            $next = $item.next();
        } else {
            $next = $(".item").first();
        }
    } else {
        if ($item.prev().length > 0) {
            $next = $item.prev();
        } else {
            $next = $(".item").last();
        }
    }
    $item.fadeOut(function () {
        $next.fadeIn();
    });
}

Updated DEMO