dav*_*ave 10 jquery loops hover
我需要一种方法来执行某种'whileonmouseover'功能,以便在鼠标覆盖元素时继续动画...
例如,给定此功能:
$(document).ready(function()
{
function doAlert()
{
alert(1);
}
$('#button').hover(function()
{
doAlert();
});
});
Run Code Online (Sandbox Code Playgroud)
当鼠标悬停在#button上时,警报将触发一次.当鼠标停留在#button上时,我需要一种方法来继续发出警报
我已经尝试做某种函数递归来继续警报,直到设置一个触发器导致它停止:
$(document).ready(function()
{
var doLoop = true;
function doAlert()
{
if (!doLoop) return;
alert(1);
doAlert();
}
$('#button').hover(function()
{
doAlert();
}, function()
{
doLoop = false;
});
});
Run Code Online (Sandbox Code Playgroud)
但那失败了.似乎该函数完全忽略'hover off'中的'doLoop = false'赋值.
有没有办法实现这个目标?
Lob*_*ity 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);
}
);
});
Run Code Online (Sandbox Code Playgroud)
我建议将以下部分移到 $(document).ready() 函数的范围之外:
var doLoop = true;
function doAlert()
{
if (!doLoop) return;
alert(1);
doAlert();
}
Run Code Online (Sandbox Code Playgroud)
所以试试这个代码:
var doLoop = true;
function doAlert()
{
if (!doLoop) return;
alert(1);
doAlert();
}
$(document).ready(function()
{
$('#button').hover(function()
{
doAlert();
}, function()
{
doLoop = false;
});
});
Run Code Online (Sandbox Code Playgroud)