2011-12-02 84 views
1

我有一個jQuery函數是這樣的:jQuery的:停止動畫的鼠標

$(function() 
var ticker = function() 
{ 
    setTimeout(function(){ 
    $('#ticker li:first').animate({marginTop: '-22px'}, 250, function() 
    { 
     $(this).detach().appendTo('ul#ticker').removeAttr('style');}); 
     ticker(); 
    }, 1500);  
}; 

$('#ticker').hover(function() { 
    $('#ticker').stop();   
}); 

ticker(); 

}); 

我試圖阻止鼠標動畫在使用.stop() API,並播放動畫,當鼠標移動了,但我沒有關於這個的想法。請幫忙。

UPDATE: 解決:http://jsbin.com/ilated

+0

要清楚:你能夠停止動畫,但需要能夠在mouseout上恢復它? –

回答

1

您可能還需要在.hover()功能clearTimeout()調用,以清除已經運行超時。然後在.hover(函數(第二個參數)的'mouseout'部分,再撥打ticker()以重新啓用它。

以下是未經測試:

var ticker_timeout = false; 
$(function() 
var ticker = function() 
{ 
    ticker_timeout = setTimeout(function(){ 
    $('#ticker li:first').animate({marginTop: '-22px'}, 250, function() 
    { 
     $(this).detach().appendTo('ul#ticker').removeAttr('style');}); 
     ticker(); 
    }, 1500);  
}; 

$('#ticker').hover(function() { 
    $('#ticker li:first').stop(); 
    clearTimeout(ticker_timeout);  
}, function() { 
    ticker(); 
}); 

ticker(); 

}); 

編輯:adeneo是正確的,你需要停止被動畫的元素。固定上述

+0

謝謝,它像一個魅力。 –

1

您需要停止在動畫元素:

$('#ticker li:first').stop(); 

此外,懸停接受兩個函數,而不是一個,你需要停止循環。

0

hover可以採取2個回調,一個用於mouseenter,另一個用於mouserleave。你可以嘗試這樣的事情。在停止動畫之後,您還應該清除超時(如果有)。

$(function() 
var timerId; 
var ticker = function() 
{ 
    timerId = setTimeout(function(){ 
    $('#ticker li:first').animate({marginTop: '-22px'}, 250, function() 
    { 
     $(this).detach().appendTo('ul#ticker').removeAttr('style');}); 
     ticker(); 
    }, 1500);  
}; 

$('#ticker').hover(function() { 
    $('#ticker li:first').stop();   
    clearTimeout(timerId); 
}, ticker); 

ticker(); 

});