jQuery - 如何在鼠标悬停在某个元素上时继续动画? [英] jQuery - How can I continue an animation while the mouse hovers over an element?

查看:113
本文介绍了jQuery - 如何在鼠标悬停在某个元素上时继续动画?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一种方法来执行某种'whileonmouseover'功能,以便在鼠标悬停在某个元素上的情况下继续进行动画... 例如,给定这个函数:

$ $ $ $ $ $ $ $ $ $ $ $($)
{
alert(1);
}

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

当鼠标悬停在#button上时,警报将会启动一次。我需要一种方法来继续让这种警报火力,而鼠标仍然在#button ...

我尝试做某种函数递归来继续警报,直到

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

函数doAlert()
{
if(!doLoop)return;
$ b $ alert(1);
doAlert();
}

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

但是失败了。似乎函数完全忽略了'悬停'中的'doLoop = false'赋值。



有什么办法可以达到这个目的?



类似于:

  var hoverInterval; 

函数doStuff(){
//将按钮的背景设置为随机颜色
$(#button).css(background,#+ Math。 floor(Math.random()* 16777215).toString(16));


$(函数(){
$(#button)。hover(
函数(){
//每次调用doStuff 100毫秒
hoverInterval = setInterval(doStuff,100);
},
function(){
//停止调用doStuff
clearInterval(hoverInterval);
}
);
});


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?

解决方案

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

这篇关于jQuery - 如何在鼠标悬停在某个元素上时继续动画?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆