jquery - 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/
任何帮助,将不胜感激
解决方案
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>
推荐阅读
- java - 在 couchbase 中保存枚举名称而不是值
- postgresql - Postgresql 我想根据今天(1 年的价值)从年、月和日数据中排除周末
- docker - Docker保存:没有这样的图像
- http - 在针对具有可读流的 Fetch 评估 SSE 时,我应该注意哪些模糊/语义差异?
- html-email - 是否可以在 Mailchimp 电子邮件模板中加入交互式元素
- javascript - 从 JSON JS 获取名称
- python - Pip 如何使用标签 >= 特定标签从 git 安装?
- java - 在 Java 中的 hashmap 中 Reteun obj
- html - 如何垂直向上增加班级的高度?
- r - ggplot2图例点没有正确着色