悬停摆动效果:如何在mouseleave上停止自调用功能?

时间:2019-02-12 18:41:10

标签: jquery loops setinterval

我正在尝试复制在信息页面底部的Bureau.cool网站上的悬停状态中找到的摆动文本 https://bureau.cool/#!/info

这是我到目前为止的位置: https://codepen.io/isaidicanshout/pen/QYxxJV

我最初尝试将CS​​S动画与添加/删除类一起使用,该类具有所需的效果,除了该效果会立即“打开”和“关闭”,而不是平稳地停止/启动。

所以我从头开始使用了无限的重复函数来切换转换:scaleY类一遍又一遍,但是一旦停止悬停,我就很难让该函数停止。

我的问题:如何创建一个在悬停时会永久重复但在停止悬停时会立即停止的函数?

// MAKES WORDS WIGGLE ON HOVER
function wiggler() {
  // Hover on .wiggle class
  $('.wiggler').hover(function(index) {
    var currentHover = $(this);
    console.log(currentHover);
    function repeatForever() {
      // Finds all spans inside the hovered element, does something after a pause
      // uses jquery-timing.min.js
      $(currentHover).children('span').each($).wait(15, function(index) {
        // Toggle the animation class
        $(this).toggleClass('ani');
      });
      // repeats forever
      window.setTimeout(repeatForever, 300);
    };
    // starts the loop
    repeatForever();
  },function() {
    var currentHover = $(this);
    console.log(currentHover);
    $(currentHover).children('span').each($).wait(15, function(index) {
      // trying to stop it from happening, but to no avail
      $(this).clearQueue().removeClass('ani');
    });
  });
};

1 个答案:

答案 0 :(得分:0)

您需要清除超时以避免无限循环:

function wiggler() {
  //note that I use this here but you could use a standard variable
  this.timeout = null
  let _this = this
  $('.wiggler').hover(function(index) {
      ...
      function repeatForever() {
       ...
         _this.timeout = window.setTimeout(repeatForever, 300);
       }
    };
    // starts the loop
    repeatForever();
  },function() {
    ...
    if (_this.timeout) window.clearTimeout(_this.timeout)
  });
};