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);
}