我有这种自动更改图像的方法,但是可以添加图像,以便在悬停时暂停,并在离开元素时重置,但是它会继续滚动而不暂停。我是JS和jQuery的新手。

JS

var galleryTimer;
var galleryTimeOut = "2500";
  var galleryImage = ".productImage";

  // auto play function to go through images
  function galleryPlay() {
    $(galleryImage).each(function(index) {
      var self = this
      galleryTimer = setTimeout(function() {
        $('.productImage').removeClass('active');
        $(self).addClass('active');
      }, index * galleryTimeOut);
    });
  }

  // pause when hovering main image and zooming image
  function galleryPause() {
    clearTimeout(galleryTimer);
  }

  // next function to move to next image
  function galleryNext() {

  }

  // prev function to move back to prevous image
  function galleryPrev() {

  }

  $(galleryImage).mouseenter(function() {
    galleryPause();
  }).mouseleave(function () {
    galleryPlay();
  });

  $('.galleryNext').on('click', function(event){

  });

  $('.galleryPrev').on('click', function(event){

  });

  // auto start the auto play
  galleryPlay();


的HTML

<ul>
  <li class="productImage active">
    <a><img src="http://placehold.it/350x350"></a>
  </li>
  <li class="productImage">
    <a><img src="http://placehold.it/350x350"></a>
  </li>
  <li class="productImage">
    <a><img src="http://placehold.it/350x350"></a>
  </li>
    <li class="productImage">
    <a><img src="http://placehold.it/350x350"></a>
  </li>
    <li class="productImage">
    <a><img src="http://placehold.it/350x350"></a>
  </li>
</ul>
<a class="galleryNext">next</a>
<a class="galleryPrev">next</a>

最佳答案

你基本上有这个

var galleryTime;
galleryTime = 1;
galleryTime = 2;
galleryTime = 3;


并且您期望该变量具有所有3个值。事实并非如此。每次迭代都会覆盖之前的迭代。

您需要一个计时器,而没有多个计时器。这是基本思想。



$( function() {
  var timer;
      lis = $(".img");

  function showNext() {
    var active = lis.filter(".active").removeClass("active");
    var next = active.next();
    if (next.length===0) {
        next = lis.eq(0);
    }
    next.addClass("active");
  }

  function playGallery() {
    stopGallery();
    timer = window.setInterval(showNext, 1000);
  }

  function stopGallery() {
    if (timer) window.clearTimeout(timer);
  }

  $(".gallery")
    .on("mouseleave", playGallery)
    .on("mouseenter", stopGallery);

  playGallery();

});

.img {
    display : none;
}

.img.active {
    display: block;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<ul class="gallery">
  <li class="img active">1</li>
  <li class="img">2</li>
  <li class="img">3</li>
  <li class="img">4</li>
  <li class="img">5</li>
</ul>

10-05 21:08
查看更多