我正在尝试创建一个功能,当您将鼠标悬停在某个对象上时,另一个对象开始持续移动,直到您输出鼠标为止。出于某些原因,在我的代码中,它在前10个像素之后停止,这就是这个,
http://jsfiddle.net/JoshuaWaheed/7df29/
$("a").mouseover(function(){
$("div").animate({
"margin-left": "+=" + 10 + "px"
});
});
如何仅在鼠标悬停时连续运行?
答案 0 :(得分:4)
尝试在这里做一个聪明的递归,
$("a").mouseover(function () {
stop = false;
animate()
});
$("a").mouseout(function () {
stop = true;
$("div").stop();
});
function animate() {
if (stop) { return; }
$("div").animate({
"margin-left": "+=" + 10 + "px"
}, animate);
}
答案 1 :(得分:2)
请勿使用.animate
,因为它不是为此而设计的。您可以通过在setInterval
循环中更改CSS来自行移动它:
$("a").mouseover(function () {
// store the interval ID on the DOM element itself
$(this).data('tc', setInterval(function () {
$("div").css({
"margin-left": "+=1"
});
}, 20) // milliseconds
);
});
$("a").mouseout(function () {
// clear the interval ID
clearInterval($(this).data('tc'));
});
答案 2 :(得分:-1)
尝试这是否有效:
var over = false;
$("a").mouseover(function(){
over = true;
while(over == true)
{
$("div").animate({
"margin-left": "+=" + 10 + "px"
});
}
});
$("a").mouseout(function(){
over = false;
});