【问题标题】:jQuery mouseleave and clearInterval not workingjQuery mouseleave 和 clearInterval 不起作用
【发布时间】:2014-03-03 04:21:11
【问题描述】:

我开始使用 SVG 图像,我制作了两个齿轮,它们应该打开 .mouseenter() 并停止在 .mouseleave() 上。通过 setInterval 函数进行翻转。 我有一个奇怪的问题,因为在 Linux Chromium 上一切正常。在 Linux Firefox 和 Windows 上,Chrome 和 Firefox 齿轮不会在 mouseLeave 上停止,而是在 mouseEnter 上加速。我正在尝试 .hover() 和 .mouseenter()/mouseLeave() 方法。

我的代码:

$(document).ready(function(){
    var deg = 0;
    var rotate_right = $('#cog1 use');
    var rotate_left = $('#cog2 use');
    var interval;
        $("#cogs").hover(
            function(){
                interval = setInterval(function(){
                if(deg >= 360) deg = 0;
                    deg += 1;
                    rotate_right.attr('transform', 'rotate('+deg+',32,32)');
                    rotate_left.attr('transform', 'rotate('+-deg+',32,32)');
            }, 10);
            },
            function(){
                clearInterval(interval);
            }
        );
});

我的JSfiddle

【问题讨论】:

  • 这取决于你如何将鼠标悬停在它上面。看起来你的容器上有一个洞,所以如果你从左到右在中心上方移动,它会在有机会清除旧的间隔之前设置一个新的间隔。我在鼠标输入部分添加了一个清除间隔(检查 null 并在清除后设置为 null)并观察会发生什么:jsfiddle.net/UM88Y/2

标签: jquery html jquery-hover mouseenter mouseleave


【解决方案1】:

问题在于您的悬停功能。

即使您在 div#cogs 上移动鼠标也会发生悬停。

这会添加一个新的timeInterval,但不会调用clearInterval来清除旧的。

只需添加 if(interval) clearInterval(interval); 到悬停函数的第一行。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-08-02
    • 2013-03-05
    • 1970-01-01
    • 2012-10-31
    • 2021-05-18
    • 2023-04-02
    • 2023-01-15
    • 2012-12-17
    相关资源
    最近更新 更多