如何解决mouseleave 的停止功能
我遇到了一个在 mouseenter 上触发并且循环的函数的问题。问题是我想在鼠标离开时停止。
尝试了一些东西,但似乎没有任何效果。
HTML
<div class="trigger">Hover me to trigger animation</div>
<div class="logo-tagline">
<span>Simple.</span>
<span>Fast.</span>
<span>Around you.</span>
</div>
JQuery
$( ".trigger" ).mouseenter(function() {
function highlight(items,index) {
index = index % items.length;
items.removeClass("-visible");
items.eq(index).addClass('-visible');
setTimeout(function() {
highlight(items,index + 1)
},1000);
}
highlight($('.logo-tagline span'),0);
});
链接到我的笔:https://codepen.io/Vlasin/pen/YzZxqNp?editors=1010
解决方法
-
你只需要清除
setTimeout
,如下 -
请注意,根据您是否要再次隐藏文本取决于您,因此请相应地处理。
let timeoutFunc; function highlight(items,index) { index = index % items.length; items.removeClass("-visible"); items.eq(index).addClass('-visible'); timeoutFunc = setTimeout(function() { highlight(items,index + 1) },1000); } $( ".trigger" ).mouseenter(function() { highlight($('.logo-tagline span'),0); }); $( ".trigger" ).mouseleave(function() { $('.-visible').removeClass("-visible"); clearTimeout(timeoutFunc); });
检查这个工作示例: https://codepen.io/DibashSapkota/pen/YzZxrXw?editors=0010
$( ".trigger" ).mouseenter(startInterval);
$( ".trigger" ).mouseleave(stopInterval);
// You'll need a variable to store a reference to the timer
var timer = null;
function startInterval() {
/* Your Function Code HERE */
// Then you initilize the variable
timer = setInterval(function() {
console.log("Foo Executed!");
},1500);
}
function stopInterval() {
// To cancel an interval,pass the timer to clearInterval()
clearInterval(timer);
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。