首页 > 解决方案 > mouseenter 上的 setInterval 和 mouseleave 上的清除间隔

问题描述

我正在使用 setInterval 使用本教程创建从 mouseenter 开始的 diy 幻灯片: https ://www.amideveloper.com/how-to-start-slideshow-on-hover-image-in-jquery/

它工作正常,但我希望幻灯片通过使用 clearInterval 在鼠标离开时停止。

我不知道我做错了什么,我的时间间隔没有被清除并且幻灯片不会停止......

这是我的代码:

查询

$(".fadeInOut > div:gt(0)").hide();

function change_div() {

  $(".fadeInOut > div:first").fadeOut(0).next().fadeIn(0).end().appendTo(".fadeInOut");

}

$(".fadeInOut").mouseenter(function(){

    myVar = setInterval(change_div, 600);
  change_div();

});

$(".fadeInOut").mouseleave(function(){

  clearInterval(myVar);

});

HTML

<div class="fadeInOut">
    <div><img src="https://www.amideveloper.com/wp-content/themes/amideveloper/slide/slider-1.jpg"></div>
    <div><img src="https://www.amideveloper.com/wp-content/themes/amideveloper/slide/slider-2.jpg"></div>
    <div><img src="https://www.amideveloper.com/wp-content/themes/amideveloper/slide/slider-3.jpg"></div>
</div>

CSS

.fadeInOut > div {
    position: absolute;
}

这是一个 jsfidlle 的链接:

https://jsfiddle.net/0ysg3r67/

任何帮助,将不胜感激

标签: jquerysetintervalmouseentermouseleaveclearinterval

解决方案


var myVar;

$(".fadeInOut").mouseenter(function(){
  clearInterval(myVar);
  myVar = setInterval(change_div, 600);
  change_div();
});

您的幻灯片转换导致 mouseenter 重新触发,创建多个间隔。为了防止这种情况发生,请尝试在创建新间隔之前清除间隔。

作为替代方案,您可以简单地标记可见的幻灯片,而不是在幻灯片中移动,并使用它来知道接下来应该显示哪张幻灯片。这似乎解决了 Firefox 一遍又一遍地触发 mouseenter 的问题。

var myVar;
var $slides = $('.fadeInOut > div');

$(".fadeInOut > div:not(.current)").hide();

function change_div() {
	var $current = $slides.filter('.current');
  var $next = ($current.next().length ? $current.next() : $slides.first());
  
  $current.fadeOut(0).removeClass('current');
  $next.addClass('current').fadeIn(0);
}

$(".fadeInOut").mouseenter(function(){
	console.log('start');

	myVar = setInterval(change_div, 600);
  change_div();

});

$(".fadeInOut").mouseleave(function(){
  console.log('stop');
  clearInterval(myVar);

});
.fadeInOut > div {
    position: absolute;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="fadeInOut">
	<div class="current"><img src="https://www.amideveloper.com/wp-content/themes/amideveloper/slide/slider-1.jpg"></div>
	<div><img src="https://www.amideveloper.com/wp-content/themes/amideveloper/slide/slider-2.jpg"></div>
	<div><img src="https://www.amideveloper.com/wp-content/themes/amideveloper/slide/slider-3.jpg"></div>
</div>


推荐阅读