2011-04-29 31 views
1

我有一種圖像滑塊的recusive功能。js/jQuery - 按鼠標位置退出功能

function nextCol(col) { 
    $('.menubox_col').fadeOut(); 
    $('.menubox_col').eq(col).fadeIn(function(){ 
    col++; 
    if (col > 3) col = 0; 
    setTimeout(function(){ nextCol(col) }, 1000); 
    }); 
} 

<div id="menubox">  
     <div class="menubox_col">content</div> 
     <div class="menubox_col">content</div> 
     <div class="menubox_col">content</div> 
     <div class="menubox_col">content</div> 
</div> 

這工作正常。但當鼠標光標進入#menubox div時,我發現沒有辦法停止遞歸函數。有任何想法嗎?

回答

0

雖然你可以使用clearTimeout,然後再次重新啓動動畫,你可以簡單地設置一個標誌,這意味着你不需要停止和啓動定時器...當鼠標在menubox上方時,這將停止動畫,並在它離開時繼續播放。我還冒昧地做了一些小的代碼更改 - 我發現結果更簡單:

$(function(){ 

    var col = 0, hover = false; 

    function nextCol() { 
    if(hover){return;} // if their mouse is over, do nothing 
    col = (col+1) % 4; // make this a one-liner. the 4 probably shouldn't be hard-coded though, it could be $('.menubox_col').length 
    $('.menubox_col').fadeOut().eq(col).fadeIn(); 
    } 

    setInterval(nextCol, 1000); 

    $('#menubox').hover(function(){ hover=true; }, function(){ hover=false; }); 

}); 
+0

這太棒了,非常感謝! – 2011-04-29 10:11:14

+0

@波拉,很高興 – davin 2011-04-29 10:14:30

0

你可以清除使用clearTimeout超時:

var timeoutHandle = null; 

function nextCol(col) { 
    $('.menubox_col').fadeOut(); 
    $('.menubox_col').eq(col).fadeIn(function() { 
     col++; 
     if (col > 3) { col = 0; } 
     timeoutHandle = setTimeout(function() { 
      nextCol(col); 
     }, 1000); 
    }); 
} 

$('#menubox div').mouseenter(function() { 
    window.clearTimeout(timeoutHandle); 
}); 
+0

這是我的第一個想法,但它沒有奏效。在你的帖子後,我再次嘗試,將整個代碼放在$(document).ready()部分。現在它正在工作 - **非常感謝**,達林! – 2011-04-29 10:00:01