jQuery - 如何在鼠标悬停在元素上时继续动画?

10
我需要一种方法来执行某种“当鼠标悬停”函数,以便在鼠标悬停在元素上时继续动画...
例如,给定以下函数:
$(document).ready(function()
{
    function doAlert()
    {
        alert(1);
    }

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

当鼠标悬停在#button上时,警报将触发一次。我需要一种方法,在鼠标仍然悬停在#button上时继续触发该警报...

我尝试过使用某种函数递归来持续发出警报,直到设置了触发器才停止:

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

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

        alert(1);
        doAlert();
    }

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

但是失败了。看起来该函数完全忽略了“悬停关闭”中的“doLoop=false”赋值。

有什么方法可以实现这个吗?

2个回答

19

我建议使用间隔时间而不是递归,因为假设最终的解决方案不仅仅是警告,而是在执行非阻塞操作,当鼠标悬停时进行递归会很快导致内存占用和无响应。

可以尝试以下代码:

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

1
我建议将以下部分移出$(document).ready()函数的范围之外:
var doLoop = true;

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

    alert(1);
    doAlert();
}

那么,请尝试使用以下代码:

var doLoop = true;

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

    alert(1);
    doAlert();
}

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

没起作用。鼠标移开元素后,函数仍然继续循环。doLoop = false 似乎没有任何影响。 - dave
在这种情况下,从 doAlert 调用 doAlert 可能会快速导致内存占用和无响应。 - Lobstrosity
我愿意尝试其他方法。 - dave

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接