2012-03-02 51 views
0

試圖創建自定義JavaScript滑塊,它的想法是它自動循環切換4個div,每個div都有自己的不同內容。另外,在側面還有一個按鈕,當你點擊它時,它會顯示相關的div並停止。單擊按鈕以顯示內容的Javascript滑塊

但是目前有三個誤區與此 1.一旦你點擊了一個項目,過了一段時間,一旦你嘗試單擊另一個項目,則將不會把它繼續循環 2。 3.您在頁面上停留的時間越長,它在項目中循環越快。

任何幫助表示讚賞,謝謝!

http://jsfiddle.net/Ek5pQ/

+0

請降低你的問題代碼,並把它的問題,而不是來的jsfiddle的鏈接。 – Deestan 2012-03-02 15:44:36

+0

但是,通過查看代碼的一般建議是*讓循環通過重新調度自己*來永久運行。不要停下來,開始它 - 你不夠小心它的工作。改爲使用標誌控制循環。 – Deestan 2012-03-02 15:50:34

回答

1

Deestan是正確的,運行的連續環。你不分青紅皁白地創造新的計時器,必須一直在創造加速。這裏是你的代碼(http://jsfiddle.net/Ek5pQ/45/)的簡化版本:

//the variables 
var i = 1; 
var myTimer; 

function myLoop() { 
    //hide everything 
    $(".nHstuff").hide(); 
    $(".nH").removeClass("active"); 
    //show just the stuff we want 
    $("#nHstuff" + i).show(); 
    $("#nH" + i).addClass("active"); 
    //increment variables 
    i++; 

    if (i === 5) { 
     i = 1; 
    } 

    //the timer  
    myTimer = setTimeout(myLoop, 3000); 
} 
//start the loop 
myLoop(); 

//what to do if hovered over an item 
$(".nH").hover(function() { 
    clearTimeout(myTimer); 
    // clear content 
    $(".nHstuff").hide(); 
    $(".nH").removeClass("active"); 
    // show content 
    $("#nHstuff" + (this.id.substr(this.id.length - 1))).show(); 
}); 

$(".nH").mouseout(function() { 
    myLoop(); 
}); 

$(".nH").click(function() { 
    clearTimeout(myTimer); 
    i = this.id.substr(this.id.length - 1, 1); 
    //show just the stuff we want 
    $("#nHstuff" + i).show(); 
    $("#nH" + i).addClass("active"); 
    // To start looping again, call myLoop 
}); 
+0

儘管在jsfiddle中工作,快速的問題,懸停和點擊功能在我的網站不工作,可能是什麼原因? – Amy 2012-03-27 14:41:46