如何制作无限轮播JQuery?

时间:2017-04-17 16:48:45

标签: jquery html carousel infinite

我正在尝试使用JQuery创建一个无限的轮播,问题是当我转到最终图像时它只是转到白色屏幕,对此的修复将回到上一个图像,我知道这是因为每个图像在另一个之下,但是如何让它循环以便在我下一次点击后转到第一个图像,或者至少回到上一个图像?

var sliderList;
$(function() {

  var sliderWrapper = $("#slider");
  sliderList = sliderWrapper.children("ul");
  var sliderItems = sliderList.children("li");

  function animateSlider(direction, duration) {
    if (direction === "+") {
      sliderList.animate({
        "margin-left": "+=800px"
      }, duration);
    } else if (direction === "-") {
      sliderList.animate({
        "margin-left": "-=800px"
      }, duration);
    }
  }

  $(".button").on('click', function() {
    if ($(this).hasClass("back")) {
      animateSlider("+", 1000);
    } else {
      animateSlider("-", 1000);
    }
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<section id="slider">
  <ul>
    <li><img src="img/room1.jpg" alt="hotel room" /></li>
    <li><img src="img/room2.jpg" alt="hotel room" /></li>
    <li><img src="img/room3.jpg" alt="hotel room" /></li>
    <li><img src="img/room4.jpg" alt="hotel room" /></li>
  </ul>

1 个答案:

答案 0 :(得分:0)

检查sliderItem是否是列表的最后一项,然后根据+或 -

将动画设为0或结束
$(function() {

  var sliderWrapper = $("#slider");
  sliderList = sliderWrapper.children("ul");
  var sliderItems = sliderList.children("li");
  var count = 0;

  function animateSlider(direction, duration) {
    if (direction === "+") {
       if(sliderItems.length === count){
         sliderList.animate({
        "margin-left": "-=2400px"//go back to original 
      }, duration);
       }else{
          sliderList.animate({
          "margin-left": "+=800px"
          }, duration);
        }
       count++;
     }
这样的事情。然后就反过来做