2014-01-09 45 views
1

最後和第一滑動之間的空白間隙見下面的jsFiddle和代碼:使用的.next()與jQuery

function slider() { 
    var activeSlide = $(".slideshow img.active"); 
    var firstSlide = $(".slideshow img:first-of-type"); 
    var lastSlide = $(".slideshow img:last-of-type"); 
activeSlide     
    .removeClass("active")  
    .next()      
    .addClass("active");  
if (activeSlide.length === 0) { 
firstSlide.addClass("active"); 
} 
} 
setInterval(function() { 
slider(); 
}, 3000); 

一旦它到達最後一張幻燈片,有前回去的暫停和空白間隙到第一張幻燈片。

有關如何解決此問題的任何建議?當我檢查元素時,我可以看到「活動」類循環通過,但在最後一次重新出現之前,它會消失一秒鐘。

在此先感謝您的任何建議。

回答

3

問題是誰是activeSlide。 你可以像這樣改變:

activeSlide.removeClass("active"); 
// You have to update the reference for the if statement that follows!! 
activeSlide = activeSlide.next();      
activeSlide.addClass("active"); 

如果事實上,如果你做console.log($(activeSlide).attr('src'))你可以看到,因爲這個問題的4張圖片,然後undefined。 像這樣應該可以工作,我在玩jsfiddle。

+0

這就是一個!感謝您的回覆,謝謝! – Pete

1

的變化 - DEMO - http://jsfiddle.net/UfNZ2/4/

activeSlide = activeSlide     
    .removeClass("active")  
    .next();      
    activeSlide.addClass("active");  

原因的變化,當您使用下面的代碼

activeSlide     
    .removeClass("active")  
    .next()      
    .addClass("active");  

    if (activeSlide.length === 0) { 
    firstSlide.addClass("active"); 
    } 

當你在最後一張幻燈片,您的代碼不會找到下一張幻燈片,並且不會不會更新任何內容,因爲activeSlide變量在if條件之前沒有更新,這意味着activeSlide仍然指向最後一張幻燈片並且其長度= 1,因此條件未通過,並且空白進入之間

1

原因將間隙:

當你在最後一張幻燈片:

activeSlide.removeClass("active").next().addClass("active"); 

地排除active類。此時您沒有任何有效幻燈片(即沒有顯示任何內容)。

並在下一行,你正在做的:

// this will not be 0 at this point as activeSlide is still the last slide 
if (activeSlide.length === 0) { 
    firstSlide.addClass("active"); // this won't be executed as activeSlide.length is 1 
} 

只有3秒,這意味着3秒鐘的時間沒有顯示幻燈片時之後再重新運行該功能。這是你看到的延遲。

解決方案:相反,你應該做的:

if (activeSlide.next().length === 0) { 
    firstSlide.addClass("active"); 
} 

更新演示:http://jsfiddle.net/UfNZ2/5/

+0

很好的解釋 - 謝謝! – Pete