jQuery在mouseenter和mouseout上暂停计时器无法正常工作

时间:2016-04-07 23:44:29

标签: javascript jquery html css

我有这种自动更改的图像,但是可以添加,因此它会在悬停时暂停并在离开元素时重置,但它会继续滚动并且不会暂停。我是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>

1 个答案:

答案 0 :(得分:1)

你基本上有这个

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>