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

て烟熏妆下的殇ゞ 提交于 2019-12-30 02:11:07

问题


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:

$(document).ready(function()
{
    function doAlert()
    {
        alert(1);
    }

    $('#button').hover(function()
    {
        doAlert();
    });
});

The alert will fire once as the mouse hovers over #button. I need a way to continue having that alert fire while the mouse remains over #button...

I've tried doing some kind of function recursion to continue the alert until a trigger is set causing it to stop:

$(document).ready(function()
{
    var doLoop = true;

    function doAlert()
    {
        if (!doLoop) return;

        alert(1);
        doAlert();
    }

    $('#button').hover(function()
    {
        doAlert();
    }, function()
    {
        doLoop = false;
    });
});

But that failed. Seems the function completely ignores the 'doLoop = false' assignment in 'hover off'.

Any way to accomplish this?


回答1:


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



回答2:


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


来源:https://stackoverflow.com/questions/2331439/jquery-how-can-i-continue-an-animation-while-the-mouse-hovers-over-an-element

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