jQuery - 当鼠标悬停在元素上时,如何继续动画? [英] jQuery - How can I continue an animation while the mouse hovers over an element?
问题描述
我需要一种方法来执行某种whileonmouseover"功能,以便在鼠标悬停在元素上时继续动画...
I need a way to perform some kind of 'whileonmouseover' function to continue an animation while the mouse overs over an element...
例如,给定这个函数:
$(document).ready(function()
{
function doAlert()
{
alert(1);
}
$('#button').hover(function()
{
doAlert();
});
});
当鼠标悬停在#button 上时,警报将触发一次.我需要一种方法来在鼠标停留在#button 上方时继续发出警报...
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;
});
});
但这失败了.似乎该函数完全忽略了悬停"中的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.
类似:
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屋!