jQuery 关于点击问题的简单幻灯片

jQuery Simple Slideshow on click issue

我正在尝试使用 jQuery 创建图像幻灯片。我有 4 张照片、一个 上一个按钮 和一个 下一个按钮 。上一个和下一个按钮正在工作,它们正在移动图像 -=400px 和 +=400px。但是我想当我在第一张照片上并且用户单击上一个按钮将他带到最后一张照片时,如果用户在最后一张照片上并单击下一个按钮将他带到第一张照片。希望有人能帮助解决这个问题

谢谢。

HTML代码:

<div class="images">
        <div class="images_inside">
            <img src="imgs/model_01.jpg">
            <img src="imgs/model_02.jpg">
            <img src="imgs/model_04.jpg">
            <img src="imgs/model_05.jpg">
        </div>
    </div>

CSS代码:

.images {
    width:400px;
    height:400px;
    border:1px solid #000000;
    overflow: hidden;
}

.images_inside {
    width:1600px;
    height:400px;
}

.images img {
    width:400px;
    height:400px;
    float:left;
}

jQuery代码:

$(".next").on("click", function(){
    var $a = $(".images .images_inside").css("margin-left", "-=400px");
});

$(".prev").on("click", function(){
    var $b = $(".images .images_inside").css("margin-left", "+=400px");
});

您可以制作一个可以更新的全局 JS 变量,让您知道用户当前在哪个图像上。然后在 on click 函数中查看变量,如果您在第一张图片上并单击上一张,则以不同方式更新边距以跳转到最后一张图片。最后一张图片上的下一个按钮也是如此。

据我了解,您对 jQuery 很陌生。

您尝试实现此目标的方式是错误的,即使您将其付诸实践。

我建议你看看 this website 并使用一些 jQuery 插件。

网站底部也有不同的例子如何自己实现。

涉及的数学很简单,
计算 tot 幻灯片数量并使用 counter

var $gallery = $(".images_inside"),
    tot = $("> *", $gallery).length,
    counter = 0;

$(".prev, .next").on("click", function() {

    // Increment/decrement the counter depending on the clicked button:
    counter = $(this).hasClass("next") ? ++counter : --counter;
    // Let's fix the counter loop
    counter = counter<0 ? tot-1 : counter%tot;

    // Finally ainmate your gallery using CSS!
    $gallery.css({
        transition: "0.5s",
        transform: "translateX(-"+  (100*counter)  +"%)"
    });

});
.images {overflow:hidden; white-space: nowrap; font-size:0;}
.images_inside>* {width: 100%;display: inline-block; vertical-align:top;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="images">
  <div class="images_inside">
    <img src="//placehold.it/400x80/cf5?text=1">
    <img src="//placehold.it/400x80/f5c?text=2">
    <img src="//placehold.it/400x80/5ff?text=3">
    <img src="//placehold.it/400x80/fc5?text=4">
  </div>
</div>
<button class="prev">&larr;</button>
<button class="next">&rarr;</button>

jsBin demo (compact code version)