jQuery - How can I continue an animation while the mouse hovers over an element?

后端 未结 2 375
一生所求
一生所求 2020-12-30 08:56

I need a way to perform some kind of \'whileonmouseover\' function to continue an animation while the mouse overs over an element...

For example, given this function

相关标签:
2条回答
  • 2020-12-30 09:36

    I would suggest to move the following part outside the scope of the $(document).ready() function:

    var doLoop = true;
    
    function doAlert()
    {
        if (!doLoop) return;
    
        alert(1);
        doAlert();
    }
    

    So try this code instead:

    var doLoop = true;
    
    function doAlert()
    {
        if (!doLoop) return;
    
        alert(1);
        doAlert();
    }
    
    $(document).ready(function()
    {
        $('#button').hover(function()
        {
            doAlert();
        }, function()
        {
            doLoop = false;
        });
    });
    
    0 讨论(0)
  • 2020-12-30 09:43

    I'd recommend setting an interval instead of recursing because, assuming the final solution isn't just alerting but is doing something non-blocking, recursing while hovering can quickly cause memory hogging and unresponsiveness.

    Something like:

    var hoverInterval;
    
    function doStuff() {
        // Set button's background to a random color
        $("#button").css("background", "#" + Math.floor(Math.random() * 16777215).toString(16));
    }
    
    $(function() {
        $("#button").hover(
            function() {
                // call doStuff every 100 milliseconds
                hoverInterval = setInterval(doStuff, 100);
            },
            function() {
                // stop calling doStuff
                clearInterval(hoverInterval);
            }
        );
    });
    
    0 讨论(0)
提交回复
热议问题