【问题标题】:clearInterval not working on mouseleaveclearInterval 在 mouseleave 上不起作用
【发布时间】:2017-08-10 20:43:39
【问题描述】:

我想链接颜色以在悬停时连续更改,但它永远不会按照我想要的方式工作 - 它不会在 mouseleave/hover out 时停止,您可以在此 fiddle 中看到:

  var interv;

  function changeColors(item) {
    interv = setInterval(function() {
      $(item).animate({
          color: 'red'
        }, 1000)
        .animate({
          color: 'green'
        }, 1000);
    }, 100);
  };

  $(document).ready(function() {

    $('a')
      .mouseenter(function() {
        changeColors(this);
      })
      .mouseleave(function() {
        clearInterval(interv);
        $(this).removeAttr("style");
      });


  });

然后我尝试重新创建 comment 的建议,但正如您在 fiddle 中看到的那样,它也不起作用:

    $(document).ready(function() {
  var interval;
  $('a').hover(
    function() {
      if (interval)
        clearInterval(interval);
      interval = setInterval(function() {
        $('a').animate({
            color: 'red'
          }, 1000)
          .animate({
            color: 'green'
          }, 1000);
      }, 10);
    },
    function() {
      clearInterval(interval);
      interval = null;
      $(this).removeAttr("style");
    }
  );
});

【问题讨论】:

  • 嗯...您的间隔为 0...它不起作用,因为您在鼠标移出时已将数千个动画排队。它会一直持续到它完成你开始的所有动画。对于这里的工作来说,间隔是错误的工具。
  • 见鬼,使用 jquery 动画可能也是错误的工具。您可以单独使用 css 获得相同的效果,并使用类打开/关闭它。 Here's a question asking how to do the animation with css alone,将其与类结合起来应该很容易。

标签: javascript jquery


【解决方案1】:

您需要在 CSS 中设置转场,这些转场处理您的动画:

a {
  transition: all 1000ms ease-in-out;
  -webkit-transition: all 1000ms ease-in-out;
}

在JS文件中你只需通过jQuery设置CSS,而不是依赖.animate(),这样你就可以通过CSS控制简单的动画了:

var int;

function changeColors(item, currentColor) {
    int = setInterval(function() {

        $(item).css({
            color: currentColor
        }, 1000)

        if (currentColor == 'red') {
            currentColor = 'green';
        } else {
            currentColor = 'red';
        }

    }, 1000);
};

$(document).ready(function() {

    $('a').mouseenter(function() {

        changeColors(this, 'red');

    });

    $('a').on('mouseleave', function() {

        $(this).removeAttr('style');
        clearInterval(int);

    });
});

对于那些想用随机颜色做类似事情的人:

Random color generator

【讨论】:

    猜你喜欢
    • 2014-03-03
    • 2023-01-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-17
    • 2021-05-18
    • 1970-01-01
    相关资源
    最近更新 更多