jQuery mouseleave and clearInterval not working

北战南征 提交于 2019-12-11 10:43:34

问题


I'm starting to play with SVG images, I've made two gearwheels which should turn on .mouseenter() and stop on .mouseleave(). Turning is made by setInterval function. I have a strange problem because on Linux Chromium everything works well. On Linux Firefox and Windows Chrome and Firefox gearwheels aren't stopping on mouseLeave and speed up on mouseEnter. I was trying both .hover() and .mouseenter()/mouseLeave() methods.

My code:

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

My JSfiddle


回答1:


the problem is in your hover function.

Hover happens even when you move your mouse on the div#cogs.

This will add a new timeInterval, but the clearInterval is not called to clear the old one.

Just add if(interval) clearInterval(interval); to the first line of hover function.



来源:https://stackoverflow.com/questions/21599228/jquery-mouseleave-and-clearinterval-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!