【问题标题】:Stop function on mouseleavemouseleave 上的停止功能
【发布时间】:2021-05-27 05:19:02
【问题描述】:

我遇到了在 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

【问题讨论】:

    标签: jquery foreach mouseleave


    【解决方案1】:
    • 你只需要清除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);
        });
      

    【讨论】:

    • 你能帮我删除 mouseleave 上的“-visible”类吗?
    • 非常感谢!
    【解决方案2】:

    检查这个工作示例: 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);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-12-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-25
      • 1970-01-01
      相关资源
      最近更新 更多