暂停jQuery on Hover

时间:2017-10-06 15:59:32

标签: javascript jquery html css

我只是希望能够在鼠标悬停时暂停动画。我试图找到这样做的好方法,但有一些问题。我测试了一些悬停/停止功能,但我无法正常工作。

jQuery(document).ready(function() {
  setInterval(function() {
    jQuery('#testimonials .slide').filter(':visible').fadeOut(1000, function() {
      if (jQuery(this).next('.slide').size()) {
        jQuery(this).next().fadeIn(1000);
      } else {
        jQuery('#testimonials .slide').eq(0).fadeIn(1000);
      }
    });
  }, 5000);
});
#quote {
  width: 100%;
  height: 130px;
  background-position: center bottom;
  background-repeat: no-repeat;
  margin-bottom: 65px;
  overflow: hidden;
}

#testimonials .slide {
  color: #555555;
}

#testimonials .testimonial-quote {
  display: inline;
  width: 600px;
  height: 170px;
  margin: 0;
  padding: 0;
  float: left;
  position: relative;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="quote">
  <div id="testimonials">
    <div class="slide">
      <div class="testimonial-quote">
        <p>Text 1</p>
        <h4 class="title">Title 1</h4>
      </div>
    </div>
  </div>
</div>

1 个答案:

答案 0 :(得分:3)

您可以通过在幻灯片悬停时调用clearInterval()来实现此目的,然后在鼠标离开幻灯片时再次重新创建间隔,如下所示:

&#13;
&#13;
jQuery(document).ready(function($) {
  var $slides = $('#testimonials .slide');
  
  function beginSlideInterval() {
    return setInterval(function() {
      $slides.filter(':visible').fadeOut(1000, function() {
        var $next = $(this).next().length ? $(this).next() : $slides.first();
        $next.fadeIn(1000);
      });
    }, 3000);
  }
 
  var slideInterval = beginSlideInterval();
  
  $slides.on('mouseenter', function() {
    clearInterval(slideInterval);
  }).on('mouseleave', function() {
    slideInterval = beginSlideInterval();
  });
});
&#13;
#quote {
  width: 100%;
  height: 130px;
  background-position: center bottom;
  background-repeat: no-repeat;
  margin-bottom: 65px;
  overflow: hidden;
}

#testimonials .slide {
  color: #555555;
}

#testimonials .testimonial-quote {
  display: inline;
  width: 600px;
  height: 170px;
  margin: 0;
  padding: 0;
  float: left;
  position: relative;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="quote">
  <div id="testimonials">
    <div class="slide">
      <div class="testimonial-quote">
        <p>Text 1</p>
        <h4 class="title">Title 1</h4>
      </div>
    </div>
  </div>
</div>
&#13;
&#13;
&#13;

请注意,我缩短了间隔以使效果更明显。