点击问题上的jQuery简单幻灯片

时间:2016-04-15 14:28:26

标签: jquery slideshow

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

感谢。

HTML code:

<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");
});

3 个答案:

答案 0 :(得分:1)

The math involved is quite simple,
Calculate the tot number of slides and use a 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)

答案 1 :(得分:0)

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

答案 2 :(得分:0)

据我所知,你对jQuery很新鲜。

即使您要使其发挥作用,您尝试实现此目标的方式也是错误的。

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

该网站还有不同的例子,如何在底部实现它。